Sometimes, we want to call Node.js fs.readFileSync with a relative path.
In this article, we’ll look at how to call Node.js fs.readFileSync with a relative path.
How to call Node.js fs.readFileSync with a relative path?
To call Node.js fs.readFileSync with a relative path, we can call path.resolve with __dirname combined with the relative path.
For instance, we write
const path = require("path");
const file = fs.readFileSync(path.resolve(__dirname, "../file.xml"));
to call fs.readFileSync with the absolute path created by calling path.resolve with __dirname and '../file.xml'.
This will return the absolute path to file.xml which we can use to call readFileSync.
Conclusion
To call Node.js fs.readFileSync with a relative path, we can call path.resolve with __dirname combined with the relative path.