简体   繁体   English

如何将值附加到 NodeJS 中的 PATH 环境变量?

[英]How to append values to the PATH environment variable in NodeJS?

Following the answer suggested in the question -按照问题中建议的答案 -

Is it possible to permanently set environment variables? 是否可以永久设置环境变量?

I was able to set new environment variables permanently with the command -我能够使用命令永久设置新的环境变量 -

spawnSync('setx', ['-m', 'MyDownloads', 'H:\\temp\\downloads'])

But now my goal is to append new values to the PATH environment variable.但现在我的目标是将新值附加到 PATH 环境变量中。

Is it possible?是否可以?

Run your script with the admin permission:使用管理员权限运行您的脚本:

  • Open cmd or PowerShell with admin用管理员打开 cmd 或 PowerShell
  • Run node your_script.js运行node your_script.js
  • To append PATH variable, you can set value is : %PATH%;your_new_value here ( %PATH% get old value)要附加PATH变量,您可以设置值是: %PATH%;your_new_value here ( %PATH% get old value)

If you run with electron app, you should require admin permission.如果您使用电子应用程序运行,您应该需要管理员权限。

Don't forget setx run on window不要忘记在窗口上运行setx

在此处输入图片说明

Why don't you just get the environment variable and then append to it?为什么不直接获取环境变量然后附加到它?

Ie IE

const {spawnSync} = require("child_process");
const current_value = process.env.PATH;
const new_path_value = current_value.concat(";", "/some/new/path");

var result = spawnSync('setx', ['-m', 'PATH', new_path_value])

// STDOUT
var stdOut = result.stdout.toString();
console.log(stdOut)

// STDERR
var stdErr =  result.stderr.toString();

if(stdErr === '') {
    console.log('Successfully set environment variable')
} else {
    console.log(`ERROR: ${stderr}`)
}

Update "/some/new/path" and run this as admin as the link you provided suggests and it should work.更新“/some/new/path”并按照您提供的链接以管理员身份运行它,它应该可以工作。

I don't have rights to modify my registry, and I also would rather not call an OS command such as setx .我无权修改我的注册表,而且我也不想调用诸如setx类的操作系统命令。

The following adds an additional component to the Windows PATH.以下内容向 Windows PATH 添加了一个附加组件。 I then ran Selenium, which uses the new setting.然后我运行了使用新设置的 Selenium。

// Display current value of PATH
const current_value = process.env.PATH;
console.log("PREV VALUE:")
console.log(current_value)

// Add the additional entry
const addl_entry = String.raw`\my\new\path\component`
process.env["PATH"] = addl_entry + ";" + current_value

// Display the new value
console.log("NEW VALUE:")
console.log(process.env.PATH)

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

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