Open and Read a file with Node.js

Tutorial Difficulty Level    

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

The usage of this method is:

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

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

Now create filesystem.js in the same manner.

Run it with
The output should not come as a surprise:
Use fs.unlink() method to delete your file(s) when done. ie.
For example: