In this post we will show about show to Node.js work with file system how to open, read, write and append text. Node.js includes fs module to access physical file system. The fs module is responsible for all the asynchronous or synchronous file I/O operations.
To read text from this use method fs.readFileSync()
var fs = require('fs'); var data = fs.readFileSync('file.txt', 'utf8'); console.log(data);
Use fs.writeFile() method to write data to a file. If file already exists then it overwrites the existing content otherwise it creates a new file and writes data into it.
var fs = require('fs'); fs.writeFile('test.txt', 'Hello World!', function (err) { console.log('Write operation complete.'); });
use fs.appendFile() method to append the content to an existing file.
var fs = require('fs'); fs.appendFile('test.txt', 'text will be append', function (err) { console.log('Append operation complete.'); });