Node.js child_process 无法访问全局模块 [英] Node.js child_process has no access to global modules
问题描述
我已经在我的 Kubuntu 19.04 中全局安装了一个 npm 包
I have installed a npm packages globally in my Kubuntu 19.04
$ npm install -g cordova
/home/username/.npm-global/bin/cordova -> /home/username/.npm-global/lib/node_modules/cordova/bin/cordova
+ cordova@9.0.0
updated 1 package in 7.299s
我可以从shell访问它
I can access it from shell
$ cordova -v
9.0.0 (cordova-lib@9.0.1)
但是我无法从带有 spawn
的简单节点脚本中访问它:
But I can't access it from a simple node script with spawn
:
const { spawn } = require( 'child_process' );
const cmd = spawn( 'cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
运行结果如下:
$ node test1.js
events.js:298
throw er; // Unhandled 'error' event
^
Error: spawn cordova ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: -2,
code: 'ENOENT',
syscall: 'spawn cordova',
path: 'cordova',
spawnargs: [ '-v' ]
}
但是当使用绝对路径时:
But when using absolute path:
const { spawn } = require( 'child_process' );
const cmd = spawn( '/home/username/.npm-global/bin/cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
我得到了预期的结果:
$ node test1.js
stdout: 9.0.0 (cordova-lib@9.0.1)
我上面的脚本只是一个测试用例,因为我在 vue-cli-plugin-cordova
和 quasar<中添加/运行
cordova
特定内容时遇到问题/代码>.我追查到,全局路径是问题所在.
My script above is just a testcase, since I have problem to add/run cordova
specific stuff in vue-cli-plugin-cordova
and quasar
. I tracked it down, that the global path is the problem.
我想我发现了问题,但不知道如何解决.将/bin/bash 设置为 shell 时,它可以工作:
I think I found the problem, but not sure how to solve it. When setting /bin/bash as shell, it works:
cmd = spawn('cordova', ['-v'], {
shell: '/bin/bash'
});
不确定,为什么需要这样做以及为什么包 vue-cli-plugin-cordova
和 quasar
不这样做.
Not sure, why this is needed and why the packages vue-cli-plugin-cordova
and quasar
don't do it.
推荐答案
好的,经过几个小时的研究和试用,我已经卸载了 node,安装了 nvm 和最新的 node,设置
Ok, after hours of research and tryouts, I have uninstalled node, installed nvm and latest node, set
nvm use --delete-prefix v13.7.0 --silent >> /dev/null
并将其添加到 ~/.bashrc
现在一切正常
这篇关于Node.js child_process 无法访问全局模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!