Node.js File Writing with fs.writeFile() - Simple Guide
To write a file using the fs module in Node.js, you can use the 'fs.writeFile()' method. Here is an example:
const fs = require('fs');
const data = 'This is some text that will be written to a file.';
fs.writeFile('example.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
In this example, we first require the 'fs' module. We then define a string of text that we want to write to the file.
We use the 'fs.writeFile()' method to write the data to the file. The first argument is the file name, the second argument is the data to be written, and the third argument is a callback function that will be called once the file has been written.
If there is an error during the write operation, an exception will be thrown. Otherwise, the callback function will be called and we print a message to the console to indicate that the file has been saved.
原文地址: https://www.cveoy.top/t/topic/oAwd 著作权归作者所有。请勿转载和采集!