Skip to content

Working with file descriptors in Node

How to interact with file descriptors using Node

Before you’re able to interact with a file that sits in your filesystem, you must get a file descriptor.

A file descriptor is what’s returned by opening the file using the open() method offered by the fs module:

const fs = require('fs')

fs.open('/Users/flavio/test.txt', 'r', (err, fd) => {
  //fd is our file descriptor
})

Notice the r we used as the second parameter to the fs.open() call.

That flag means we open the file for reading.

Other flags you’ll commonly use are

You can also open the file by using the fs.openSync method, which instead of providing the file descriptor object in a callback, it returns it:

const fs = require('fs')

try {
  const fd = fs.openSync('/Users/flavio/test.txt', 'r')
} catch (err) {
  console.error(err)
}

Once you get the file descriptor, in whatever way you choose, you can perform all the operations that require it, like calling fs.open() and many other operations that interact with the filesystem.

→ Download my free Node.js Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: