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');
  }
});
  1. Import the File System module in Node.js (fs) to handle file operations.

  2. Define the file path (logFilePath) where you want to store the log file. For instance, it's set to 'log.txt'.

  3. 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.

  4. Use the fs.appendFile() method to append the logMessage to the file specified by logFilePath. This method takes in the file path, the content to append (in this case, logMessage), and a callback function.

  5. Inside the callback function, check if there's an error during the file write operation. If an error occurs (err is not null), log the error message using console.error.

  6. If the write operation is successful, log a confirmation message using console.log.