nodejs write to log file
const fs = require('fs');
const logFilePath = 'log.txt';
const logMessage = 'This is a log message.\n';
fs.appendFile(logFilePath, logMessage, (err) => {
if (err) {
console.error('Error writing to log file:', err);
} else {
console.log('Message appended to log file');
}
});
Import the File System module in Node.js (
fs
) to handle file operations.Define the file path (
logFilePath
) where you want to store the log file. For instance, it's set to'log.txt'
.Define the log message (
logMessage
) that you want to append to the log file. Ensure to include\n
at the end for a new line.Use the
fs.appendFile()
method to append thelogMessage
to the file specified bylogFilePath
. This method takes in the file path, the content to append (in this case,logMessage
), and a callback function.Inside the callback function, check if there's an error during the file write operation. If an error occurs (
err
is notnull
), log the error message usingconsole.error
.If the write operation is successful, log a confirmation message using
console.log
.