I'm writing a NPM module for a cli-based tool. After someone installs the package, I need to read their package.json
file. I know how to read the file in syntax. My question is, how can I consistenly retrieve the package.json
file and should I use relative or absolute paths.
我正在为基于cli的工具编写NPM模块。有人安装包后,我需要读取他们的package.json文件。我知道如何在语法中读取文件。我的问题是,我如何能够一致地检索package.json文件,我应该使用相对路径还是绝对路径。
So, after installing, my code would reside somewhere inside the node_modules
folder:
因此,安装后,我的代码将驻留在node_modules文件夹中的某个位置:
package.json // I need to require this file
node_modules/
↳ my-package/
↳ dist/
↳ my-package.js // the actual file running the code
Any suggestions/best practices? Or is it just a matter of using the right filepath?
有什么建议/最佳实践吗?或者只是使用正确的文件路径?
1 个解决方案
#1
2
Reading the package.json file is very easy, as you can simply require it:
读取package.json文件非常简单,因为您只需要它:
var package = require('./path/to/package.json');
Finding the right path is what's not so simple.
找到正确的道路并不是那么简单。
This is quite a common task and there is no simple way to achieve that with core modules but there are few modules on npm that can help you with that.
这是一个非常常见的任务,并没有简单的方法来实现核心模块,但npm上的几个模块可以帮助你。
find-package-json:
Easily find package.json files that you're searching for. It spiders parent directories for package.json files and correctly reads the results. It follows an ES6 iterator design so it should be easy to implement.
轻松找到您要搜索的package.json文件。它spiders package.json文件的父目录并正确读取结果。它遵循ES6迭代器设计,因此应该易于实现。
parent-package-json:
Using parent-package-json, you can find the parent package.json, so the package.json of the module that uses your module.
使用parent-package-json,您可以找到父package.json,因此使用您的模块的模块的package.json。
find-and-read-package-json:
Find and read data from a package.json file.
从package.json文件中查找和读取数据。
See:
#1
2
Reading the package.json file is very easy, as you can simply require it:
读取package.json文件非常简单,因为您只需要它:
var package = require('./path/to/package.json');
Finding the right path is what's not so simple.
找到正确的道路并不是那么简单。
This is quite a common task and there is no simple way to achieve that with core modules but there are few modules on npm that can help you with that.
这是一个非常常见的任务,并没有简单的方法来实现核心模块,但npm上的几个模块可以帮助你。
find-package-json:
Easily find package.json files that you're searching for. It spiders parent directories for package.json files and correctly reads the results. It follows an ES6 iterator design so it should be easy to implement.
轻松找到您要搜索的package.json文件。它spiders package.json文件的父目录并正确读取结果。它遵循ES6迭代器设计,因此应该易于实现。
parent-package-json:
Using parent-package-json, you can find the parent package.json, so the package.json of the module that uses your module.
使用parent-package-json,您可以找到父package.json,因此使用您的模块的模块的package.json。
find-and-read-package-json:
Find and read data from a package.json file.
从package.json文件中查找和读取数据。
See: