3. Reading and Writing Files in Node.js
3. Reading and Writing Files in Node.js
- Node.js provides the
fs(File System) module to interact with the file system for reading and writing files. - It includes both
asynchronousandsynchronousmethods for working with files
Reading Files
- Synchronous File Reading
readFileSyncis the synchronous method for reading files, it only takes the file location and the file encoding- This will block code execution until the file has been read
- In applications where performance is critical, it’s often preferred to use the
asynchronousversion, but thesynchronousversion can be a lot easier to reason about - Example
const data = fs.readFileSync('example.txt', 'utf8'); console.log(data);- This will block the code until the entire contents of
example.txtare read, and then print out the contents.
- This will block the code until the entire contents of
- Asynchronous File Reading
readFileis the asynchronous method for reading files, it take the file location and encoding, same as the synchronous method. However, it also takes acallbackfunction which will be ran after the file contents are read- The callback function takes two parameters when it is ran, an
Errorobject (in case an error occurs while reading) and astringcontaining the file contents - Example
fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });- This will not block the code, but when the reading of
example.txthas finished, the data will be printed or the error (if applicable)
Writing Files
- Synchronous File Writing
writeFileSync(likereadFileSync) is the synchronous method for writing files- Again, it will block execution until the file has been written and it is often preferred to use the asynchronous version if performance is an issue
- Asynchronous File Writing
- Simular to
readFilethe asyncrhonous counterpart for writing iswriteFile writeFilealso takes acallbackfunction (like it’sreadFilecounterpart), however this callback only takes anerrorparameter, as there is no data to return
- Simular to
Common Errors
- When working with files, there are many opportunities for error
- It’s important to be aware of this, and do your best to handle at least some of the common errors
- File not found: An extremely common error that occurs when the file attemtping to be read, or written to, does not exist.
- Surrounding any particular code in a try/catch block can help
- You can also check if a file exists with something like
existsSync
- Inadequate permssions: Another common errors that occurs when you don’t have the proper permissions to perform the asked file operation
- The best method for this error is to use standard error handling like a try/catch statement or checking the error object in the async callback