File System

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.

Reading File

Use fs.readFile() method to read the physical file asynchronously.Signature:

fs.readFile(fileName [,options], callback)
  • filename: Full path and name of the file as a string.

  • options: The options parameter can be an object or string which can include encoding and flag. The default encoding is utf8 and default flag is "r".

  • callback: A function with two parameters err and fd. This will get called when readFile operation completes.

  • options: "utf8"

Reading existing TestFile.txt asynchronously.Example: Reading File Copy

var fs = require('fs');

fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;

    console.log(data);
});

$.getJSON('http://example.com/ajax', function (data) {
    console.log('IO...');
});
console.log('No wait for IO...');

Asychronize reading

If option is null, Buffer object return. we can use

Sync read file:

readfile

stat

fs.stat(),

Last updated

Was this helpful?