有没有办法从“package.json”获取版本? Node.js 代码中的文件?
有没有办法获取 package.json 中设置的版本。 Node.js 应用程序中的 json 文件?我想要这样的东西
var port = process.env.PORT || 3000
app.listen port
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, app.VERSION
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
或者在普通的旧外壳中:
这可以缩短为
Or in plain old shell:
This can be shortened to
检索版本的方法有两种:
package.json
和获取版本:请不要使用
JSON.parse
、fs .readFile
、fs.readFileSync
并且不要使用其他npm 模块
,这个问题没有必要。There are two ways of retrieving the version:
package.json
and getting the version:Please don't use
JSON.parse
,fs.readFile
,fs.readFileSync
and don't use anothernpm modules
it's not necessary for this question.对于那些寻找也适用于服务器端的安全客户端解决方案的人来说,有genversion。它是一个命令行工具,可以从最近的 package.json 读取版本并生成导出该版本的可导入 CommonJS 模块文件。免责声明:我是维护者。
我承认客户端安全不是 OP 的主要意图,但正如 Mark Wallace 和 aug,它是高度相关的,也是我找到这个问答的原因。
For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.
I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.
以下是如何从 package.json 中读取版本:
在其他答案中,可能最干净的是:
这是 ES6 版本:
Here is how to read the version out of package.json:
Of other answers, probably the cleanest is:
Here's the ES6 version:
NPM oneliner:
来自npm v7.20.0:
npm pkg get version
在 npm v7.20.0 之前:
npm -s run env echo '$npm_package_version'
请注意,这两种方法的输出略有不同:前者输出用引号括起来的版本号(即
"1.0.0"
),后者不带引号(即1.0.0
)。在 Unix 中删除引号的一种解决方案是使用 xargs
NPM one liner:
From npm v7.20.0:
npm pkg get version
Prior to npm v7.20.0:
npm -s run env echo '$npm_package_version'
Note the output is slightly different between these two methods: the former outputs the version number surrounded by quotes (i.e.
"1.0.0"
), the latter without (i.e.1.0.0
).One solution to remove the quotes in Unix is using
xargs
还有另一种方法可以从 package.json 文件中获取某些信息,即使用 pkginfo 模块。
该模块的使用非常简单。您可以使用以下方式获取所有包变量:
或者仅获取某些详细信息(在本例中为
version
):并且您的包变量将设置为
module.exports
(因此版本号将可以通过 module.exports.version 访问)。您可以使用以下代码片段:
该模块具有非常好的功能。它可以在项目中的任何文件中使用(例如,在子文件夹中),并且它将自动从您的 package.json 文件中获取信息。因此,您不必担心 package.json 文件在哪里。
There is another way of fetching certain information from your package.json file, namely using the pkginfo module.
Usage of this module is very simple. You can get all package variables using:
Or only certain details (
version
in this case):And your package variables will be set to
module.exports
(so the version number will be accessible viamodule.exports.version
).You could use the following code snippet:
This module has very nice feature. It can be used in any file in your project (e.g., in subfolders) and it will automatically fetch information from your package.json file. So you do not have to worry where your package.json file is.
选项 1
最佳实践是使用 npm 环境变量从 package.json 进行版本控制。
更多信息: https://docs.npmjs.com/using-npm/config.html
仅当您使用 NPM 命令启动服务时,这才有效。
选项 2
使用 https://www.npmjs.com/package/dotenv 作为
.env
文件并将其读取为process.env。版本
Option 1
Best practice is to version from package.json using npm environment variables.
more information on: https://docs.npmjs.com/using-npm/config.html
This will work only when you start your service using NPM command.
Option 2
Setting version in environment variable using https://www.npmjs.com/package/dotenv as
.env
file and reading it asprocess.env.version
我们可以通过两种方式从
package.json
读取版本或其他密钥1-使用
require
并导入所需的密钥,例如:2-使用 package_vars 如文档中所述
we can read the version or other keys from
package.json
in two ways1- using
require
and import the key required e.g:2 - using package_vars as mentioned in doc
只是添加一个答案,因为我来到这个问题是为了了解将 package.json 中的版本包含在我的 Web 应用程序中的最佳方法。
我知道这个问题是针对 Node.js 的,但是,如果您使用 Webpack 捆绑您的应用程序,只是提醒一下,推荐的方法是使用 DefinePlugin 在配置中声明全局版本并引用它。因此,您可以在
webpack.config.json
中执行操作,然后
AppVersion
现在是可供您使用的全局变量。另请确保在您的.eslintrc
中通过全局属性Just adding an answer because I came to this question to see the best way to include the version from package.json in my web application.
I know this question is targetted for Node.js however, if you are using Webpack to bundle your app just a reminder the recommended way is to use the DefinePlugin to declare a global version in the config and reference that. So you could do in your
webpack.config.json
And then
AppVersion
is now a global that is available for you to use. Also make sure in your.eslintrc
you ignore this via the globals prop一个安全的选择是添加一个 npm 脚本来生成单独的版本文件:
这会输出
version.js
内容:A safe option is to add an npm script that generates a separate version file:
This outputs
version.js
with the contents:您可以使用ES6导入package.json来检索版本号并在控制台输出版本。
You can use ES6 to import package.json to retrieve version number and output the version on console.
如果您正在寻找
module (package.json: "type": "module")
(ES6 import) 支持,例如来自重构 commonJS,您应该(在撰写本文时)执行以下任一操作:或者,使用
node --experimental-json-modules index.js
运行节点进程来执行以下操作:但是,您会收到警告,直到 json 模块变得普遍可用。
如果您收到语法或(顶级)异步错误,则您可能使用的是较旧的节点版本。至少更新到node@14。
If you are looking for
module (package.json: "type": "module")
(ES6 import) support, e.g. coming from refactoring commonJS, you should (at the time of writing) do either:or, run the node process with
node --experimental-json-modules index.js
to do:You will however get a warning, until json modules will become generally available.
If you get Syntax or (top level) async errors, you are likely in a an older node version. Update to at least node@14.
要确定节点代码中的包版本,可以使用以下命令:
const version = require('./package.json').version;
forconst version = require('./package.json').version;
ES6 版本import {version} from './package.json';
对于 ES6 版本const version = process.env.npm_package_version;
如果应用程序已使用
npm start
启动,则所有 npm_* 环境变量都可用。您也可以使用以下 npm 包 - root-require、pkginfo、project-version。
To determine the package version in node code, you can use the following:
const version = require('./package.json').version;
for < ES6 versionsimport {version} from './package.json';
for ES6 versionconst version = process.env.npm_package_version;
if application has been started using
npm start
, all npm_* environment variables become available.You can use following npm packages as well - root-require, pkginfo, project-version.
为什么不使用 require resolve...
这种方法适用于所有子路径:)
Why don't use the require resolve...
With this approach work for all sub paths :)
我正在使用
create-react-app
,但在执行 React-app 时没有可用的process.env.npm_package_version
。我不想在我的客户端代码中引用
package.json
(因为向客户端暴露危险信息,例如包版本),我也不想安装另一个依赖项(genversion)。我发现我可以通过在 package.json 中使用
$npm_package_version
来引用package.json
中的version
:现在版本始终遵循
package.json
中的那个。I'm using
create-react-app
and I don't haveprocess.env.npm_package_version
available when executing my React-app.I did not want to reference
package.json
in my client-code (because of exposing dangerous info to client, like package-versions), neither I wanted to install an another dependency (genversion).I found out that I can reference
version
withinpackage.json
, by using$npm_package_version
in my package.json:Now the version is always following the one in
package.json
.您可以使用 project-version 包。
然后
它使用 process.env.npm_package_version ,但会回退到 package.json 中编写的版本,以防环境变量由于某种原因丢失。
You can use the project-version package.
Then
It uses
process.env.npm_package_version
but fallback on the version written in thepackage.json
in case the env var is missing for some reason.我知道这不是OP的意图,但我不得不这样做,所以希望它能帮助下一个人。
如果您使用 Docker Compose 进行 CI/CD流程,可以这样搞定!
对于图像,您可以使用任何 Node.js 图像。我使用 Alpine Linux,因为它是最小的。
I know this isn't the intent of the OP, but I just had to do this, so hope it helps the next person.
If you're using Docker Compose for your CI/CD process, you can get it this way!
For the image, you can use any Node.js image. I use Alpine Linux, because it is the smallest.
我发现的最精简的方法:
The leanest way I found:
如果您想获取目标包的版本。
示例:
In case you want to get version of the target package.
Example:
实际上,我已经尝试过这里的大多数解决方案,它们要么在 Windows 和 Linux/OSX 上都不起作用,要么根本不起作用,要么依赖于 grep/awk/sed 等 Unix shell 工具。
接受的答案在技术上可行,但它会将整个 package.json 吸进您的构建中,这是一件坏事,只有绝望的人才应该使用,暂时解锁,并且通常应该避免,至少用于生产代码。一种替代方法是使用该方法仅将版本写入可用作构建源文件的单个常量,而不是整个文件。
因此,对于任何其他正在寻找跨平台解决方案(不依赖于 Unix shell 命令)和本地解决方案(没有外部依赖项)的人来说:
由于可以假设已安装 Node.js,并且它已经是跨平台的,所以我只是使用以下命令创建了一个
make_version.js
文件(或在较新的环境中为make_version.cjs
):并向
package 添加了一个
:version
命令。 json或
(对于CommonJS 文件),然后添加:
它会在每次
start
或build
上创建一个新的src/versions.js
。当然,这可以在version
脚本中轻松调整为不同的位置,或者在make_version.js
文件中输出不同的语法和常量名称等。另请注意pnpm 包管理器不会自动运行“pre”脚本,因此如果使用该 PM,您可能需要调整两个命令。
I've actually been through most of the solutions here and they either did not work on both Windows and Linux/OSX, or didn't work at all, or relied on Unix shell tools like grep/awk/sed.
The accepted answer works technically, but it sucks your whole package.json into your build and that's a Bad Thing that only the desperate should use, temporarily to get unblocked, and in general should be avoided, at least for production code. One alternative is to use that method only to write the version to a single constant that can be used as a source file for the build, instead of the whole file.
So for anyone else looking for a cross-platform solution (not reliant on Unix shell commands) and local (without external dependencies):
Since it can be assumed that Node.js is installed, and it's already cross-platform for this, I just created a
make_version.js
file (ormake_version.cjs
in more recent environments) with:and added a
version
command topackage.json
:or
(for a CommonJS file) and then added:
and it creates a new
src/versions.js
on everystart
orbuild
. Of course this can be easily tuned in theversion
script to be a different location, or in themake_version.js
file to output different syntax and constant name, etc.Note also that the pnpm package manager does not automatically run "pre" scripts, so you might need to adjust it for two commands if using that PM.
我正在使用 gitlab ci 并希望自动使用不同的版本来标记我的 docker 镜像并推送它们。现在,他们的默认 docker 映像不包含节点,因此我仅在 shell 中执行此操作的版本是
script/getCurrentVersion.sh
现在,它的作用是
请注意,我的脚本位于存储库中具有相应名称的子文件夹中,因此,如果您不将 $BASEDIR/../package.json 更改为 $BASEDIR/package.json
或者如果您希望能够获得专业,次要版本和补丁版本 如果您的版本是 1.2.3,我会这样使用
script/getCurrentVersion.sh
您的输出将如下所示
现在您唯一需要确保的是您的软件包版本将是软件包中的第一次。 .json 使用该密钥,否则您将得到错误的版本
I am using gitlab ci and want to automatically use the different versions to tag my docker images and push them. Now their default docker image does not include node so my version to do this in shell only is this
scripts/getCurrentVersion.sh
Now what this does is
Please not that i have my scripts in a subfolder with the according name in my repository. So if you don't change $BASEDIR/../package.json to $BASEDIR/package.json
Or if you want to be able to get major, minor and patch version I use this
scripts/getCurrentVersion.sh
this way if your version was 1.2.3. Your output would look like this
Now the only thing you will have to make sure is that your package version will be the first time in package.json that key is used otherwise you'll end up with the wrong version
我使用
findup-sync
执行此操作:I do this with
findup-sync
:我编写了一个有用的代码来获取父模块的 package.json
I made a useful code to get the parent module's package.json
如果使用 rollup,则可以使用 rollup-plugin-replace 插件添加版本,而无需向客户端公开 package.json。
然后,在源代码中,任何想要使用 package.json 版本的地方,都可以使用字符串“MY_PACKAGE_JSON_VERSION”。
If using rollup, the
rollup-plugin-replace
plugin can be used to add the version without exposing package.json to the client.Then, in the source code, anywhere where you want to have the package.json version, you would use the string 'MY_PACKAGE_JSON_VERSION'.
将
package.json
文件导入到server.js
或app.js
中,然后将 package.json 属性访问到服务器文件中。package 变量包含 package.json 中的所有数据。
Import your
package.json
file into yourserver.js
orapp.js
and then access package.json properties into server file.package variable contains all the data in package.json.
此代码假设您的 package.json 文件位于 Node.js 应用程序的根目录中。如果它位于不同的目录中,请相应地调整所需路径。
这会将 package.json 中指定的版本记录到控制台。您可以根据需要在应用程序中使用 appVersion 变量。
This code assumes that your package.json file is in the root directory of your Node.js application. If it's located in a different directory, adjust the require path accordingly.
This will log the version specified in your package.json to the console. You can use the appVersion variable in your application as needed.
我发现以下代码片段最适合我。由于它使用
require
加载package.json
,因此无论当前工作目录如何,它都可以正常工作。警告,由 @Pathogen 提供:
I found that the following code fragment worked best for me. Since it uses
require
to load thepackage.json
, it works regardless of the current working directory.A warning, courtesy of @Pathogen:
如果您的应用程序是使用
npm start
启动的,您只需使用:请参阅 package.json vars 了解更多详细信息。
If your application is launched with
npm start
, you can simply use:See package.json vars for more details.
使用 ES6 模块,您可以执行以下操作:
Using ES6 modules, you can do the following: