In this tutorial, we’ll learn how to read a file with Node.js.
As Node.js gives us access to to operating system level functionality it’s possible to read from files directly from the file system (unlike browser based JavaScript) in a similar way to other server-side languages.
You can either do this synchronously or asynchronously.
The synchronous method is probably the simplest and most common use-case for reading a file, especially if you want to save the data in to a variable.
const { readFileSync } = require('fs');
const data = readFileSync('./file.json', 'utf8');
console.log(data);
Note if you pass the file encoding in as the second parameter, you will get the contents of the file otherwise you will receive a buffer that you will need to read from.
But you need to be careful with this approach as if there is a problem reading the file (i.e. it doesn’t exist) then the above code will throw an error so you need to check for this.
For example you could do something like this:
const { readFileSync } = require('fs');
let data;
try {
data = readFileSync('./package.json1', 'utf8');
} catch (error) {
data = 'Error Reading File';
}
console.log(data);
With the asynchronous version of readFile
you pass in a callback as the final argument to the function. This takes two arguments, the first will contain an error (if any occurs) and the second is the data of the file.
const { readFile } = require('fs');
readFile('./package.json', 'utf8', (error, data) => {
if (error) {
// Handle the error
return console.log(error);
}
// Do something with data
console.log(data);
});
If you’re using promises in your code, you can wrap the asynchronous readFile
function in a promise with the promisify
function.
const { readFile } = require('fs');
const { promisify } = require('util');
const readFilePromise = promisify(readFile);
readFilePromise('./package.jso1n', 'utf8')
.then((data) => {
// Do something with data
console.log(data)
})
.catch((error) => {
// Handle the error
console.log(error);
});