Fs.readFileSync doesn't apply to files? Node.js
-Please, I have a file in the root of my project called "file.xml"
-Please, I have a test file in tests / called "test.js" and it has
const file = fs.readFileSync("../file.xml");
If now I run node ./tests/test.js
from the root of my project, it says: ../ file.xml does not exist. If I run the same command from the tests directory, then it works.
It seems fs.readFileSync refers to the directory from which the script is called, not where the script is being called. If I wrote fs.readFileSync("./file.xml")
in test.js it would look more confusing and not match relative paths in the require statement that are relative to the files.
Why is this?
How do I avoid rewriting the paths in my fs.readFileSync?
source to share
You can resolve the path relative to the location of the source file - not the current directory - using path.resolve
:
const path = require("path");
const file = fs.readFileSync(path.resolve(__dirname, "../file.xml"));
source to share