How to read and write a file in Node.js

Node implements File I/O using simple wrappers around standard POSIX functions.

Every method in fs module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where as the second one does.

Read file

// Asynchronous read
var fs = require('fs');
fs.readFile(file, [encoding], [callback]);
  • file - filepath of the file to read
  • encoding is an optional parameter that specifies the type of encoding to read the file. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding is provided, the default is utf8.
  • callback is a function to call when the file has been read and the contents are ready - it is passed two arguments, error and data. If there is no error, error will be null and data will contain the file contents; otherwise err contains the error message.

Examples

// Asynchronous read
fs.readFile('/tmp/movies.txt', function (err, data) {
   if (err) {
       return console.error(err);
   }
   console.log("Data: " + data.toString());
});

// Synchronous read
var data = fs.readFileSync('/tmp/movies.txt');
console.log("Data: " + data.toString());

Read JSON file

var fs = require('fs')
var dataRaw = fs.readFileSync("/tmp/movies.json")
var dataJSON = JSON.parse(dataRaw)

Write file

Writing to a file is another of the basic programming tasks that one usually needs to know about. We can use the handy writeFile method inside the standard library's fs module.

var fs = require('fs');
var fs.writeFile(filename, data, [options], [callback])

This method will over-write the file if file already exists. If you want to write into an existing file then you should use another method available.

var fs = require('fs');
fs.writeFile('/tmp/hw.txt', 'Hello World!', function (err) {
  if (err) return console.log(err);
  console.log('Wrote!');
});

Write JSON file

var fs = require('fs');
var movie = {title: 'The Shawshank Redemption (1994)', rating: 9.2};
fs.writeFile('/tmp/movie.json', JSON.stringify(movie), function (err) {
  if (err) return console.log(err);
  console.log('Wrote!');
});
comments powered by Disqus