Working with file descriptors in Node
By Flavio Copes
Learn how Node.js file descriptors work, how to open a file with the right access flag, and why you must close the descriptor when you finish.
A file descriptor is a number that identifies an open file to the operating system.
Node gives you a descriptor when you open a file with fs.open():
const fs = require('node:fs')
fs.open('/Users/flavio/test.txt', 'r', (error, fd) => {
if (error) {
console.error(error)
return
}
console.log(fd)
fs.close(fd, error => {
if (error) {
console.error(error)
}
})
})
The r flag opens the file for reading.
Other common flags are:
r+opens the file for reading and writingw+opens the file for reading and writing, creating it or truncating itaopens the file for appending, creating it if neededa+opens the file for reading and appending, creating it if needed
You can pass the descriptor to lower-level methods such as fs.read(), fs.write(), and fs.fstat().
Always close it with fs.close() when you finish. Leaving descriptors open can eventually stop the process from opening more files.
Node also provides the synchronous openSync() method. It returns the descriptor directly:
const fs = require('node:fs')
let fd
try {
fd = fs.openSync('/Users/flavio/test.txt', 'r')
console.log(fd)
} catch (error) {
console.error(error)
} finally {
if (fd !== undefined) {
fs.closeSync(fd)
}
}
Most applications should use higher-level methods such as fs.readFile() and fs.writeFile(). They manage the file descriptor for you.
Related posts about node: