Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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:
r+— open for reading and writingw+— open for reading and writing, with the stream at the start; creates the file if it does not exista— open for writing, with the stream at the end; creates the file if it does not exista+— open for reading and writing, with the stream at the end; creates the file if it does not exist
You can also use fs.openSync(), which returns the file descriptor instead of passing it to a callback:
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 reading from or writing to the file.