Node.js File System Operations - Asynchronous File Reading with fs Module

Learn how to perform asynchronous file reading in Node.js using the fs.readFile method. Explore common I/O operations with the fs module in this concise tutorial.



Node.js File System

Node.js includes the fs module to access the physical file system. The fs module is responsible for all the asynchronous or synchronous file I/O operations.

Let's see some of the common I/O operation examples using the fs module.

Reading a File

Asynchronous

Use fs.readFile(fileName, [options], callback) to read a file asynchronously.

  • fileName: Path to the file as a string.
  • options: Optional object for encoding and flags (default: utf8, r).
  • callback: Function with parameters err (error) and data (file content).

Example: Reading a File

Code Example

var fs = require('fs');

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

The above example reads TestFile.txt asynchronously and executes the callback function when the read operation completes. This read operation either throws an error or completes successfully. The err parameter contains error information if any. The data parameter contains the content of the specified file.

TextFile.txt

Content

This is a test file to test the fs module of Node.js.
        

Example Output

Output

C:\> node server.js
This is a test file to test the fs module of Node.js
        

Use the fs.readFileSync() method to read a file synchronously, as shown below.

Example: Reading File Synchronously

Code Example

var fs = require('fs');

var data = fs.readFileSync('dummyfile.txt', 'utf8');
console.log(data);
        

Synchronous

Use fs.readFileSync(fileName, 'encoding') for synchronous reading. Returns the file content as a string.

Writing a File

Use the fs.writeFile() method to write data to a file. If the file already exists, it overwrites the existing content; otherwise, it creates a new file and writes data into it.

Signature:

fs.writeFile(filename, data[, options], callback)

Parameter Description:

  • filename: Full path and name of the file as a string.
  • data: The content to be written in a file.
  • options: The options parameter can be an object or string which can include encoding, mode, 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 the write operation completes.

Example: Creating & Writing a File

Code Example

var fs = require('fs');

fs.writeFile('test.txt', 'Hello World!', function (err) { 
if (err)
    console.log(err);
else
    console.log('Write operation complete.');
});
        

In the same way, use the fs.appendFile() method to append the content to an existing file.

Example: Append Content to a File

Code Example

var fs = require('fs');

fs.appendFile('test.txt', 'Hello World!', function (err) { 
if (err)
    console.log(err);
else
    console.log('Append operation complete.');
});
        

Open File

Alternatively, you can open a file for reading or writing using the fs.open() method.

Signature:

fs.open(path, flags[, mode], callback)

Parameter Description:

  • path: Full path with the name of the file as a string.
  • flag: The flag to perform the operation.
  • mode: The mode for read, write, or readwrite. Defaults to 0666 readwrite.
  • callback: A function with two parameters err and fd. This will get called when the file open operation completes.

Flags

The following table lists all the flags which can be used in read/write operations.

Flag Description
r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if the path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if the path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the path exists.

Example: File Open and Read

Code Example

var fs = require('fs');

fs.open('TestFile.txt', 'r', function (err, fd) {
if (err) {
    return console.error(err);
}

var buffr = new Buffer(1024);

fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) {
    if (err) throw err;

    // Print only read bytes to avoid junk.
    if (bytes > 0) {
        console.log(buffr.slice(0, bytes).toString());
    }

    // Close the opened file.
    fs.close(fd, function (err) {
        if (err) throw err;
    });
});
});
        

Delete File

Use the fs.unlink() method to delete an existing file.

Signature:

fs.unlink(path, callback);

The following example deletes an existing file.

Example: Delete a File

Code Example

var fs = require('fs');

fs.unlink('test.txt', function () {
console.log('File Deleted Successfully.');
});
        

Important Methods of fs Module

Method Description
fs.readFile(fileName [,options], callback) Reads an existing file.
fs.writeFile(filename, data[, options], callback) Writes to the file. If the file exists, it overwrites the content; otherwise, it creates a new file.
fs.open(path, flags[, mode], callback) Opens a file for reading or writing.
fs.rename(oldPath, newPath, callback) Renames an existing file.
fs.chown(path, uid, gid, callback) Asynchronous chown.
fs.stat(path, callback) Returns an fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback) Links a file asynchronously.
fs.unlink(path, callback); Deletes a file.
fs.symlink(destination, path[, type], callback) Creates a symbolic link asynchronously.
fs.rmdir(path, callback) Removes an existing directory.
fs.mkdir(path[, mode], callback) Creates a new directory.
fs.readdir(path, callback) Reads the content of the specified directory.
fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file.
fs.exists(path, callback) Determines whether the specified file exists or not.
fs.access(path[, mode], callback) Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback) Appends new content to the existing file.