有没有办法从“package.json”获取版本? Node.js 代码中的文件?

发布于 2025-01-02 07:48:56 字数 359 浏览 5 评论 0 原文

有没有办法获取 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

Is there a way to get the version set in the package.json file in a Node.js application? I would want something like this

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

想你的星星会说话 2025-01-09 07:48:57

或者在普通的旧外壳中:

node -e "console.log(require('./package.json').version);"

这可以缩短为

node -p "require('./package.json').version"

Or in plain old shell:

node -e "console.log(require('./package.json').version);"

This can be shortened to

node -p "require('./package.json').version"
第七度阳光i 2025-01-09 07:48:57

检索版本的方法有两种:

  1. 需要 package.json 和获取版本:
const { version } = require('./package.json');
  1. 使用环境变量:
const version = process.env.npm_package_version;

请不要使用 JSON.parsefs .readFilefs.readFileSync 并且不要使用其他 npm 模块,这个问题没有必要。

There are two ways of retrieving the version:

  1. Requiring package.json and getting the version:
const { version } = require('./package.json');
  1. Using the environment variables:
const version = process.env.npm_package_version;

Please don't use JSON.parse, fs.readFile, fs.readFileSync and don't use another npm modules it's not necessary for this question.

朦胧时间 2025-01-09 07:48:57

对于那些寻找也适用于服务器端的安全客户端解决方案的人来说,有genversion。它是一个命令行工具,可以从最近的 package.json 读取版本并生成导出该版本的可导入 CommonJS 模块文件。免责声明:我是维护者。

$ genversion lib/version.js

我承认客户端安全不是 OP 的主要意图,但正如 Mark Wallaceaug,它是高度相关的,也是我找到这个问答的原因。

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.

$ genversion lib/version.js

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.

清旖 2025-01-09 07:48:57

以下是如何从 package.json 中读取版本:

fs = require('fs')
json = JSON.parse(fs.readFileSync('package.json', 'utf8'))
version = json.version

在其他答案中,可能最干净的是:

const { version } = require('./package.json');

这是 ES6 版本:

import {version} from './package.json';

Here is how to read the version out of package.json:

fs = require('fs')
json = JSON.parse(fs.readFileSync('package.json', 'utf8'))
version = json.version

Of other answers, probably the cleanest is:

const { version } = require('./package.json');

Here's the ES6 version:

import {version} from './package.json';
羅雙樹 2025-01-09 07:48:57

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 pkg get version | 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

npm pkg get version | xargs
北风几吹夏 2025-01-09 07:48:57

还有另一种方法可以从 package.json 文件中获取某些信息,即使用 pkginfo 模块。

该模块的使用非常简单。您可以使用以下方式获取所有包变量:

require('pkginfo')(module);

或者仅获取某些详细信息(在本例中为 version):

require('pkginfo')(module, 'version');

并且您的包变量将设置为 module.exports (因此版本号将可以通过 module.exports.version 访问)。

您可以使用以下代码片段:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, 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:

require('pkginfo')(module);

Or only certain details (version in this case):

require('pkginfo')(module, 'version');

And your package variables will be set to module.exports (so the version number will be accessible via module.exports.version).

You could use the following code snippet:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, module.exports.version

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.

短暂陪伴 2025-01-09 07:48:57

选项 1

最佳实践是使用 npm 环境变量从 package.json 进行版本控制。

process.env.npm_package_version

更多信息: https://docs.npmjs.com/using-npm/config.html

仅当您使用 NPM 命令启动服务时,这才有效。

快速信息:您可以使用 process.env.npm_package_[keyname] 读取 pacakge.json 中的任何值

选项 2

使用 https://www.npmjs.com/package/dotenv 作为 .env 文件并将其读取为 process.env。版本

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

仙女山的月亮 2025-01-09 07:48:57

我们可以通过两种方式从 package.json 读取版本或其他密钥

1-使用 require 并导入所需的密钥,例如:

const version = require('./package.json')

2-使用 package_vars 如文档中所述

process.env.npm_package_version

we can read the version or other keys from package.json in two ways

1- using require and import the key required e.g:

const version = require('./package.json')

2 - using package_vars as mentioned in doc

process.env.npm_package_version
别理我 2025-01-09 07:48:57

只是添加一个答案,因为我来到这个问题是为了了解将 package.json 中的版本包含在我的 Web 应用程序中的最佳方法。

我知道这个问题是针对 Node.js 的,但是,如果您使用 Webpack 捆绑您的应用程序,只是提醒一下,推荐的方法是使用 DefinePlugin 在配置中声明全局版本并引用它。因此,您可以在 webpack.config.json 中执行操作

const pkg = require('../../package.json');

...

plugins : [
    new webpack.DefinePlugin({
      AppVersion: JSON.stringify(pkg.version),
...

,然后 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

const pkg = require('../../package.json');

...

plugins : [
    new webpack.DefinePlugin({
      AppVersion: JSON.stringify(pkg.version),
...

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

仙气飘飘 2025-01-09 07:48:57

一个安全的选择是添加一个 npm 脚本来生成单独的版本文件:

"scripts": {
    "build": "yarn version:output && blitz build",
    "version:output": "echo 'export const Version = { version: \"'$npm_package_version.$(date +%s)'\" }' > version.js"
  }

这会输出 version.js 内容:

export const Version = { version: "1.0.1.1622225484" }

A safe option is to add an npm script that generates a separate version file:

"scripts": {
    "build": "yarn version:output && blitz build",
    "version:output": "echo 'export const Version = { version: \"'$npm_package_version.$(date +%s)'\" }' > version.js"
  }

This outputs version.js with the contents:

export const Version = { version: "1.0.1.1622225484" }
放赐 2025-01-09 07:48:57

您可以使用ES6导入package.json来检索版本号并在控制台输出版本。

import {name as app_name, version as app_version}  from './path/to/package.json';

console.log(`App ---- ${app_name}\nVersion ---- ${app_version}`);

You can use ES6 to import package.json to retrieve version number and output the version on console.

import {name as app_name, version as app_version}  from './path/to/package.json';

console.log(`App ---- ${app_name}\nVersion ---- ${app_version}`);
苏别ゝ 2025-01-09 07:48:57

如果您正在寻找 module (package.json: "type": "module") (ES6 import) 支持,例如来自重构 commonJS,您应该(在撰写本文时)执行以下任一操作:

import { readFile } from 'fs/promises';

const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url)));

console.log(pkg.version)

或者,使用 node --experimental-json-modules index.js 运行节点进程来执行以下操作:

import pkg from './package.json'
console.log(pkg.version)

但是,您会收到警告,直到 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:

import { readFile } from 'fs/promises';

const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url)));

console.log(pkg.version)

or, run the node process with node --experimental-json-modules index.js to do:

import pkg from './package.json'
console.log(pkg.version)

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.

枫林﹌晚霞¤ 2025-01-09 07:48:57

要确定节点代码中的包版本,可以使用以下命令:

  1. const version = require('./package.json').version; for

    const version = require('./package.json').version; ES6 版本

  2. import {version} from './package.json'; 对于 ES6 版本

  3. const version = process.env.npm_package_version;
    如果应用程序已使用 npm start 启动,则所有 npm_* 环境变量都可用。

  4. 您也可以使用以下 npm 包 - root-require、pkginfo、project-version。

To determine the package version in node code, you can use the following:

  1. const version = require('./package.json').version; for < ES6 versions

  2. import {version} from './package.json'; for ES6 version

  3. const version = process.env.npm_package_version;
    if application has been started using npm start, all npm_* environment variables become available.

  4. You can use following npm packages as well - root-require, pkginfo, project-version.

鸢与 2025-01-09 07:48:57

为什么不使用 require resolve...

const packageJson = path.dirname(require.resolve('package-name')) + '/package.json';
const { version } = require(packageJson);
console.log('version', version)

这种方法适用于所有子路径:)

Why don't use the require resolve...

const packageJson = path.dirname(require.resolve('package-name')) + '/package.json';
const { version } = require(packageJson);
console.log('version', version)

With this approach work for all sub paths :)

泪眸﹌ 2025-01-09 07:48:57

我正在使用 create-react-app ,但在执行 React-app 时没有可用的 process.env.npm_package_version

我不想在我的客户端代码中引用 package.json (因为向客户端暴露危险信息,例如包版本),我也不想安装另一个依赖项(genversion)。

我发现我可以通过在 package.json 中使用 $npm_package_version 来引用 package.json 中的 version

"scripts": {
    "my_build_script": "REACT_APP_VERSION=$npm_package_version react-scripts start"
}

现在版本始终遵循package.json 中的那个。

I'm using create-react-app and I don't have process.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 within package.json, by using $npm_package_version in my package.json:

"scripts": {
    "my_build_script": "REACT_APP_VERSION=$npm_package_version react-scripts start"
}

Now the version is always following the one in package.json.

り繁华旳梦境 2025-01-09 07:48:57

您可以使用 project-version 包。

$ npm install --save project-version

然后

const version = require('project-version');

console.log(version);
//=>  '1.0.0'

它使用 process.env.npm_package_version ,但会回退到 package.json 中编写的版本,以防环境变量由于某种原因丢失。

You can use the project-version package.

$ npm install --save project-version

Then

const version = require('project-version');

console.log(version);
//=>  '1.0.0'

It uses process.env.npm_package_version but fallback on the version written in the package.json in case the env var is missing for some reason.

情泪▽动烟 2025-01-09 07:48:57

我知道这不是OP的意图,但我不得不这样做,所以希望它能帮助下一个人。

如果您使用 Docker Compose 进行 CI/CD流程,可以这样搞定!

version:
  image: node:7-alpine
  volumes:
    - .:/usr/src/service/
  working_dir: /usr/src/service/
  command: ash -c "node -p \"require('./package.json').version.replace('\n', '')\""

对于图像,您可以使用任何 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!

version:
  image: node:7-alpine
  volumes:
    - .:/usr/src/service/
  working_dir: /usr/src/service/
  command: ash -c "node -p \"require('./package.json').version.replace('\n', '')\""

For the image, you can use any Node.js image. I use Alpine Linux, because it is the smallest.

风苍溪 2025-01-09 07:48:57

我发现的最精简的方法:

const { version } = JSON.parse(fs.readFileSync('./package.json'))

The leanest way I found:

const { version } = JSON.parse(fs.readFileSync('./package.json'))
維他命╮ 2025-01-09 07:48:57

如果您想获取目标包的版本。

import { version } from 'TARGET_PACKAGE/package.json';

示例:

import { version } from 'react/package.json';

In case you want to get version of the target package.

import { version } from 'TARGET_PACKAGE/package.json';

Example:

import { version } from 'react/package.json';
梦回旧景 2025-01-09 07:48:57

实际上,我已经尝试过这里的大多数解决方案,它们要么在 Windows 和 Linux/OSX 上都不起作用,要么根本不起作用,要么依赖于 grep/awk/sed 等 Unix shell 工具。

接受的答案在技术上可行,但它会将整个 package.json 吸进您的构建中,这是一件坏事,只有绝望的人才应该使用,暂​​时解锁,并且通常应该避免,至少用于生产代码。一种替代方法是使用该方法仅将版本写入可用作构建源文件的单个常量,而不是整个文件。

因此,对于任何其他正在寻找跨平台解决方案(不依赖于 Unix shell 命令)和本地解决方案(没有外部依赖项)的人来说:

由于可以假设已安装 Node.js,并且它已经是跨平台的,所以我只是使用以下命令创建了一个 make_version.js 文件(或在较新的环境中为 make_version.cjs):

const PACKAGE_VERSION = require("./package.json").version;
console.log(`export const PACKAGE_VERSION = "${PACKAGE_VERSION}";`);
console.error("package.json version:", PACKAGE_VERSION);

并向 package 添加了一个 version 命令。 json

scripts: {
    "version": "node make_version.js > src/version.js",

scripts: {
    "version": "node make_version.cjs > src/version.js",

(对于CommonJS 文件),然后添加:

    "prebuild": "npm run version",
    "prestart": "npm run version",

它会在每次 startbuild 上创建一个新的 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 (or make_version.cjs in more recent environments) with:

const PACKAGE_VERSION = require("./package.json").version;
console.log(`export const PACKAGE_VERSION = "${PACKAGE_VERSION}";`);
console.error("package.json version:", PACKAGE_VERSION);

and added a version command to package.json:

scripts: {
    "version": "node make_version.js > src/version.js",

or

scripts: {
    "version": "node make_version.cjs > src/version.js",

(for a CommonJS file) and then added:

    "prebuild": "npm run version",
    "prestart": "npm run version",

and it creates a new src/versions.js on every start or build. Of course this can be easily tuned in the version script to be a different location, or in the make_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.

简美 2025-01-09 07:48:57

我正在使用 gitlab ci 并希望自动使用不同的版本来标记我的 docker 镜像并推送它们。现在,他们的默认 docker 映像不包含节点,因此我仅在 shell 中执行此操作的版本是

script/getCurrentVersion.sh

BASEDIR=$(dirname $0)
cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g'

现在,它的作用是

  1. 打印您的包 json
  2. 搜索带有“version”的行
  3. 仅获取第一个结果
  4. 替换“和,

请注意,我的脚本位于存储库中具有相应名称的子文件夹中,因此,如果您不将 $BASEDIR/../package.json 更改为 $BASEDIR/package.json

或者如果您希望能够获得专业,次要版本和补丁版本 如果您的版本是 1.2.3,我会这样使用

script/getCurrentVersion.sh

VERSION_TYPE=$1
BASEDIR=$(dirname $0)
VERSION=$(cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g')

if [ $VERSION_TYPE = "major" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1}' )
elif [ $VERSION_TYPE = "minor" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1"."$2}' )
else
  echo $VERSION
fi

您的输出将如下所示

$ > sh ./getCurrentVersion.sh major
1

gt; sh ./getCurrentVersion.sh minor
1.2

gt; sh ./getCurrentVersion.sh
1.2.3

现在您唯一需要确保的是您的软件包版本将是软件包中的第一次。 .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

BASEDIR=$(dirname $0)
cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g'

Now what this does is

  1. Print your package json
  2. Search for the lines with "version"
  3. Take only the first result
  4. Replace " and ,

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

VERSION_TYPE=$1
BASEDIR=$(dirname $0)
VERSION=$(cat $BASEDIR/../package.json | grep '"version"' | head -n 1 | awk '{print $2}' | sed 's/"//g; s/,//g')

if [ $VERSION_TYPE = "major" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1}' )
elif [ $VERSION_TYPE = "minor" ]; then
  echo $(echo $VERSION | awk -F "." '{print $1"."$2}' )
else
  echo $VERSION
fi

this way if your version was 1.2.3. Your output would look like this

$ > sh ./getCurrentVersion.sh major
1

gt; sh ./getCurrentVersion.sh minor
1.2

gt; sh ./getCurrentVersion.sh
1.2.3

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

怕倦 2025-01-09 07:48:57

我使用 findup-sync 执行此操作:

var findup = require('findup-sync');
var packagejson = require(findup('package.json'));
console.log(packagejson.version); // => '0.0.1' 

I do this with findup-sync:

var findup = require('findup-sync');
var packagejson = require(findup('package.json'));
console.log(packagejson.version); // => '0.0.1' 
小糖芽 2025-01-09 07:48:57

我编写了一个有用的代码来获取父模块的 package.json

function loadParentPackageJson() {
    if (!module.parent || !module.parent.filename) return null
    let dir = path.dirname(module.parent.filename)
    let maxDepth = 5
    let packageJson = null
    while (maxDepth > 0) {
        const packageJsonPath = `${dir}/package.json`
        const exists = existsSync(packageJsonPath)
        if (exists) {
            packageJson = require(packageJsonPath)
            break
        }
        dir = path.resolve(dir, '../')
        maxDepth--
    }
    return packageJson
}

I made a useful code to get the parent module's package.json

function loadParentPackageJson() {
    if (!module.parent || !module.parent.filename) return null
    let dir = path.dirname(module.parent.filename)
    let maxDepth = 5
    let packageJson = null
    while (maxDepth > 0) {
        const packageJsonPath = `${dir}/package.json`
        const exists = existsSync(packageJsonPath)
        if (exists) {
            packageJson = require(packageJsonPath)
            break
        }
        dir = path.resolve(dir, '../')
        maxDepth--
    }
    return packageJson
}
杀お生予夺 2025-01-09 07:48:57

如果使用 rollup,则可以使用 rollup-plugin-replace 插件添加版本,而无需向客户端公开 package.json。

// rollup.config.js

import pkg from './package.json';
import { terser } from "rollup-plugin-terser";
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace';

export default {
  plugins: [
    replace({
      exclude: 'node_modules/**',
      'MY_PACKAGE_JSON_VERSION': pkg.version, // will replace 'MY_PACKAGE_JSON_VERSION' with package.json version throughout source code
    }),
  ]
};

然后,在源代码中,任何想要使用 package.json 版本的地方,都可以使用字符串“MY_PACKAGE_JSON_VERSION”。

// src/index.js
export const packageVersion = 'MY_PACKAGE_JSON_VERSION' // replaced with actual version number in rollup.config.js

If using rollup, the rollup-plugin-replace plugin can be used to add the version without exposing package.json to the client.

// rollup.config.js

import pkg from './package.json';
import { terser } from "rollup-plugin-terser";
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace';

export default {
  plugins: [
    replace({
      exclude: 'node_modules/**',
      'MY_PACKAGE_JSON_VERSION': pkg.version, // will replace 'MY_PACKAGE_JSON_VERSION' with package.json version throughout source code
    }),
  ]
};

Then, in the source code, anywhere where you want to have the package.json version, you would use the string 'MY_PACKAGE_JSON_VERSION'.

// src/index.js
export const packageVersion = 'MY_PACKAGE_JSON_VERSION' // replaced with actual version number in rollup.config.js
谁对谁错谁最难过 2025-01-09 07:48:57
const { version } = require("./package.json");
console.log(version);

const v = require("./package.json").version;
console.log(v);

const { version } = require("./package.json");
console.log(version);

const v = require("./package.json").version;
console.log(v);

一场信仰旅途 2025-01-09 07:48:57

package.json 文件导入到 server.jsapp.js 中,然后将 package.json 属性访问到服务器文件中。

var package = require('./package.json');

package 变量包含 package.json 中的所有数据。

Import your package.json file into your server.js or app.js and then access package.json properties into server file.

var package = require('./package.json');

package variable contains all the data in package.json.

眼角的笑意。 2025-01-09 07:48:57
const packageJson = require('./package.json'); // Adjust the path if needed

const appVersion = packageJson.version;

console.log(`The version specified in package.json is: ${appVersion}`);

此代码假设您的 package.json 文件位于 Node.js 应用程序的根目录中。如果它位于不同的目录中,请相应地调整所需路径。

这会将 package.json 中指定的版本记录到控制台。您可以根据需要在应用程序中使用 appVersion 变量。

const packageJson = require('./package.json'); // Adjust the path if needed

const appVersion = packageJson.version;

console.log(`The version specified in package.json is: ${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.

白日梦 2025-01-09 07:48:56

我发现以下代码片段最适合我。由于它使用 require 加载 package.json,因此无论当前工作目录如何,它都可以正常工作。

var pjson = require('./package.json');
console.log(pjson.version);

警告,由 @Pathogen 提供:

使用 Browserify 执行此操作会产生安全隐患。
请小心,不要将您的 package.json 暴露给客户端,因为这意味着您的所有依赖项版本号、构建和测试命令等都会发送到客户端。
如果您在同一个项目中构建服务器和客户端,那么您也会公开服务器端版本号。
攻击者可以使用此类特定数据来更好地适应对您服务器的攻击。<​​/p>

I found that the following code fragment worked best for me. Since it uses require to load the package.json, it works regardless of the current working directory.

var pjson = require('./package.json');
console.log(pjson.version);

A warning, courtesy of @Pathogen:

Doing this with Browserify has security implications.
Be careful not to expose your package.json to the client, as it means that all your dependency version numbers, build and test commands and more are sent to the client.
If you're building server and client in the same project, you expose your server-side version numbers too.
Such specific data can be used by an attacker to better fit the attack on your server.

z祗昰~ 2025-01-09 07:48:56

如果您的应用程序是使用 npm start 启动的,您只需使用:

process.env.npm_package_version

请参阅 package.json vars 了解更多详细信息。

If your application is launched with npm start, you can simply use:

process.env.npm_package_version

See package.json vars for more details.

瞎闹 2025-01-09 07:48:56

使用 ES6 模块,您可以执行以下操作:

import {version} from './package.json';

Using ES6 modules, you can do the following:

import {version} from './package.json';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文