Open and Read a file with Node.js

Watch out! This tutorial is over 6 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

You can open a file for reading or writing using fs.open()method.

The usage of this method is:

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

where:

  • path: Full path with name of the file as a string.
  • flag: The flag to perform 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 file open operation completes.

The following lists all the flags which can be used in your read/write operation.

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 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 path exists.
a Open file for appending. The file is created if it does not exist.
ax Like ‘a’ but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like ‘a+’ but fails if path exists.

Let’s give it a go! Fire up Node.js Server (with MongoDB) instance on XOA and create a new text file, hello.txt

administrator@ubuntu:~$ nano hello.txt

Add some text (eg “Hello World!”) and save with ctrl + x.

Now create filesystem.js in the same manner.

var fs = require('fs');

fs.open('hello.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;
        });
    });
});

Run it with

nodejs filesystem.js

The output should not come as a surprise:

administrator@ubuntu:~$ nodejs filesystem.js 
Hello World!

Use fs.unlink() method to delete your file(s) when done. ie.

fs.unlink(path, callback);

For example:

fs.unlink('hello.txt', (err) => {
  if (err) throw err;
  console.log('hello.txt was deleted successfully');
});