I have created a npm package named test_package_cat, which is supposed to read a json file (info.json) at the beginning. Thus, index.js (main entry) and info.json are at the same level.
When I run the index.js locally, I can read the file.
either:
fs.readFileSync('info.json')
or
fs.readFileSync(path.resolve(__dirname, 'info.json')
works fine.
However, when I have another program, a React page,that uses the package, it fails to read the json file.
cat = require('test_package_cat')
cat.meow()
When I run index.js locally, if I console.log(__dirname), it gives me C://......../myProject. However, when running the React app, console.log(__dirname) just prints "/" and when I try to print directories/files, it shows nothing.
How can I make the my npm package to read info.json file?
Edit : After more searching, I managed to get it working by doing:
let info = require('./info.json')
console.log(JSON.stringify(info))
but would still like to know how to do it using "readFile" way.
fs
is only available in the Node runtime environment. It isn't available in a browser's JavaScript runtime environment. I'm surprised you haven't encountered an error to that effect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.