[英]How to upgrade a specific package inside a Node file?
I have a Node
project with the following structure:我有一个具有以下结构的
Node
项目:
.
├── index.js
├── package.json
├── updater.js
└── yarn.lock
I'm using Yarn
with this project.我在这个项目中使用
Yarn
。
Inside file: package.json
there is a reference to package: @emotion/core@^10.0.22
as you can see below:在文件:
package.json
有对包的引用: @emotion/core@^10.0.22
,如下所示:
{
"name": "my-project",
...
"dependencies": {
...
"@emotion/core": "^10.0.22",
...
}
...
}
What I need is:我需要的是:
From inside file: updater.js
file, upgrade package: @emotion/core
to version: ^10.0.27
(just in case, remember I'm using Yarn
), so I can do:从内部文件:
updater.js
文件,升级包: @emotion/core
到版本: ^10.0.27
(以防万一,记住我使用的是Yarn
),所以我可以这样做:
$ node updater.js
From the command line I can achieve this very easily with:从命令行我可以很容易地做到这一点:
$ yarn upgrade @emotion/core@^10.0.27
But I need to do this from inside the file: updater.js
(this is a requirement).但我需要从文件内部执行此操作:
updater.js
(这是一项要求)。 This is a simplification of a biggest problem (so I need to meet the requirements of this dummy use case even if it doesn't make sense).这是一个最大问题的简化(所以我需要满足这个虚拟用例的要求,即使它没有意义)。
This code will go inside a custom package that will take care of installing some other packages.此代码将放在一个自定义包中,该包将负责安装其他一些包。
Thanks in advance!提前致谢!
The easiest will be using child_process
to execute any script:最简单的方法是使用
child_process
来执行任何脚本:
const { exec } = require('child_process');
const childProcess = exec('yarn upgrade @emotion/core@^10.0.27', (error, stdout, stderr) => {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
You can check out more at node.js document page
您可以在
node.js document page
查看更多node.js document page
You can pipe the stdio for close-to-realtime outputs by doing:您可以通过执行以下操作将 stdio 用于接近实时的输出:
childProcess.stdout.pipe(process.stdout)
But beware using *Sync
(like execSync
) libraries, you should NOT
block code whenever possible.但要注意使用
*Sync
(如execSync
)库,你应该NOT
只要有可能阻止代码。 Better using callback
or make it Promise
更好地使用
callback
或使其成为Promise
Also there are wonderful packages like shelljs
to encapsulate this.还有一些很棒的包,比如
shelljs
来封装这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.