简体   繁体   English

读取 npm 包的文件

[英]Reading a file for a npm package

I have created a npm package named test_package_cat, which is supposed to read a json file (info.json) at the beginning.我创建了一个名为 test_package_cat 的 npm 包,它应该在开始时读取一个 json 文件(info.json)。 Thus, index.js (main entry) and info.json are at the same level.因此,index.js(主条目)和 info.json 处于同一级别。

When I run the index.js locally, I can read the file.当我在本地运行 index.js 时,我可以读取文件。

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.但是,当我有另一个程序,一个使用该包的React页面时,它无法读取 json 文件。

 cat = require('test_package_cat')
 cat.meow()

When I run index.js locally, if I console.log(__dirname), it gives me C://......../myProject.当我在本地运行 index.js 时,如果我使用 console.log(__dirname),它会给我 C://......../myProject。 However, when running the React app, console.log(__dirname) just prints "/" and when I try to print directories/files, it shows nothing.但是,在运行 React 应用程序时,console.log(__dirname) 只打印“/”,而当我尝试打印目录/文件时,它什么也没显示。

How can I make the my npm package to read info.json file?如何让我的 npm 包读取 info.json 文件?

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.但仍然想知道如何使用“readFile”方式来做到这一点。

fs is only available in the Node runtime environment. fs仅在 Node 运行时环境中可用。 It isn't available in a browser's JavaScript runtime environment.它在浏览器的 JavaScript 运行时环境中不可用。 I'm surprised you haven't encountered an error to that effect.我很惊讶您没有遇到这种情况的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM