Node.js has built-in module named ‘fs’ (file system) which supports creating, writing and reading files. In this tutorial we will write the code for writing a text file, appending text in a file and reading the contents of a text file. fs module supports all three operations.
Writing a text file in Node.js:
index.js:
const fs = require('fs'); fs.writeFile('./files/sample.txt', 'Nodejs - File Write example FS ' + (new Date()), function (err) { if (err) { console.log("Error occurred", err); } console.log("File write successfull"); });
The fs.writeFile() method accepts 3 parameters. First is the path of the file which is to be created and written it, second is the data to be written, third is a callback function. Important thing here to consider is that, this method will overwrite the contents a file if it is already present at the specified path. To avoid this we can use fs.appendfile() method.
fs.appendfile() – Append data to an existing file:
const fs = require('fs'); fs.appendFile('./files/sample2.txt', '\r\nNodejs - File Append example FS ' + new Date(), (err) => { if (err) { console.log("Error occurred", err); } console.log("File append successful") });
This method will append the specified data to the file.
Node.js – Reading file using fs:
The fs.readFile() method file reads the content of the specified file.
const fs = require('fs'); fs.readFile('./files/sample2.txt', 'utf8', (err, data) => { if (err) { console.log("Error occurred", err); } console.log("File read successfull. File Data", data); });