Reputation: 853
I am trying to read a file using the file-system package.
reference: https://www.npmjs.com/package/file-system
The file I am trying to read resides in the same directory as the file executing the read (visual below).
The code in the reduce2.js file is exactly this:
const fs = require('fs')
var output = fs.readFileSync('data.txt')
console.log(output);
This is the error I am getting when I run the file from the command line:
➜ js-practice node functional-programming-mpj/file-system-and-reduce/reduce2.js
fs.js:638
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT: no such file or directory, open 'data.txt'
at Object.fs.openSync (fs.js:638:18)
at Object.fs.readFileSync (fs.js:540:33)
at Object.<anonymous> (/Users/jackburum/tutorials/js-practice/functional-programming-mpj/file-system-and-reduce/reduce2.js:3:17)
at Module._compi
which tells me that the file system module can't find the file, but I can't figure out why.
Some other things I have tried: - I tried using import as well instead of require - I tried explicitly declaring the current directory, like this
fs.readFileSync('./data.txt').
Do you know what I am doing wrong or have any thoughts on what I could try to make this work?
Upvotes: 1
Views: 376
Reputation: 40374
The problem is, you're executing node
command from another directory: js-practice/
.
For fs.readFileSync('./data.txt');
to work in your case you need to run node
directly on file-system-and-reduce
dir
file-system-and-reduce $ node reduce2.js
Otherwise node tries to search: js-practice/data.txt
which doesn't exist in your case.
A good solution is to use: __dirname, along with path.join
, in order to get the absolute path to the file, which will allow you to call the script from any location.
const fs = require('fs'); // Native fs module
const path = require('path');
const output = fs.readFileSync(path.join(__dirname, 'data.txt'));
console.log(output);
Have in mind that the reference you provided, is not the native file system module.
Upvotes: 2