Writing to files in Node.js is fairly easy thanks to provided File System APIs, node fs.
Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
The encoding option is ignored if data is a buffer. It defaults to 'utf8'.
Example:
fs.writeFile('message.txt', 'Hello Node.js', function(err) {
if (err) throw err;
console.log('The file has been saved!');
});
Full Example:
1. import file system module
var fs = require('fs')
2. Now use fs to create a new file and write into it
fs.writeFile("/tmp/test.json", "{'key':'value'}", function(err) {
if(error) {
return console.log(error);
}
console.log("successfully saved test.json file");
});
Now Asynchronously reads the entire contents of a file.
fs.readFile("/tmp/test.json", function(err, data) {
if (err) throw err;
console.log(data);
});
