In Node.js, you can write data to files using the built-in fs module. fs.writeFile() function is used to writing a file asynchronously. fs.writeFileSync() function is used to writing a file synchronously.
Here's an example of how to write data to a file in Node.js:
const fs = require('fs');
const data = 'Hello, world!';
fs.writeFile('file.txt', data, (err) => {
if (err) throw err;
console.log('Data written to file');
});
In this example, we're using the writeFile function of the fs module to write the string "Hello, world!" to a file named file.txt. The first argument to writeFile is the filename, the second argument is the data to be written, and the third argument is a callback function that will be called once the data has been written (or if an error occurs). In this case, the callback function simply logs a message to the console indicating that the data has been written to the file.
Note that writeFile overwrites the file if it already exists, so be careful when using this method. If you want to append data to an existing file, you can use the appendFile method instead. Here's an example:
const fs = require('fs');
const data = 'Hello, world again!';
fs.appendFile('file.txt', data, (err) => {
if (err) throw err;
console.log('Data appended to file');
});
In this example, we're using the appendFile function to append the string "Hello, world again!" to the end of the file file.txt. The arguments to appendFile are the same as those for writeFile.
Comments (0)