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

Trying to open a file at path. callback will receive any exceptions with the operation as its first argument, and a file descriptor as its second argument. Here, we open a file for reading:

fs.open("path.js", "r", (err, fileDescriptor) => {   console.log(fileDescriptor); // An integer, like `7` or `23` }); 

flags receives a string indicating the types of operations the caller expects to perform on the returned file descriptor. Their meanings should be clear:

  • r: Opening a file for reading, throwing an exception if the file doesn't exist.
  • r+: Opening a file for both reading and writing, throwing an exception if the file doesn't exist.
  • w: Opening a file for writing, creating the file if it doesn't exist, ...

Get Mastering Node.js - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.