Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:
const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);
const readContentFile = async (filePath) => {
// Eureka, you are using good code practices here!
const content = await readFileAsync(path.join(__dirname, filePath), {
encoding: 'utf8'
})
return content;
}
Later can use this async function with try/catch from any other function:
const anyOtherFun = async () => {
try {
const fileContent = await readContentFile('my-file.txt');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
}
Happy Coding!