Node.js – How to Create, Write and Read File

  • by
node-js-file-append-example-001

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.

DOWNLOAD SAMPLE CODE

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-file-append-example-001

node-js-file-append-example-002

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);
});

nodejs-file-read-example-003

DOWNLOAD SAMPLE CODE


Also see:


  1. Base64Encode.io - Realtime Encode your string to Base64 format.
  2. Base64Decode.io - Realtime Decode Base64 data to plain text.
  3. Md5Hash.io - Realtime Encoding in Md5Hash.

2 thoughts on “Node.js – How to Create, Write and Read File”

  1. Pingback: Download Source Code No 112 - ParallelCodes

  2. Pingback: Node.js - How to create Directory | fs.mkdir() - ParallelCodes

Comments are closed.