Reputation: 437
I've got a challenge to read a txt file that located in the same directory as my app.js.
In the challenge I can't use require
so I can't import fs.readFileSync
to my app.
Looking for other ways to console.log
the txt content. Any ideas?
Upvotes: 3
Views: 8558
Reputation: 40444
Without using require
explicitly, you can use: module.constructor._load
or process.mainModule.constructor._load
const fs = module.constructor._load('fs');
console.log(fs.readFileSync('./test.txt'));
Note that process.mainModule
will be undefined
if there is no entry script. (Not your case)
Of course this shouldn't be used in production code, since it's an undocumented API and may change. But will do for your challenge.
forgot to mention that I have to run it as node app.js
Otherwise you could use ES6 modules too, but that requires an additional flag: node --experimental-modules app.js
Upvotes: 3