如何通过child_process.spawn()执行本地安装的Node.js应用程序? [英] How to execute locally installed Node.js application by child_process.spawn()?

查看:272
本文介绍了如何通过child_process.spawn()执行本地安装的Node.js应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 child_process.spawn 执行Electron应用程序:

I want to execute the Electron application by child_process.spawn:

import ChildProcess, {ChildProcess as ChildProcess__type} from 'child_process';
const childProcess: ChildProcess__type = ChildProcess.spawn(
        'electron',
        ['ProjectInitializer__ElectronMain.js'],
        { cwd: __dirname } // current project root
    );

我得到了错误:生成电子ENOENT 错误。 Electron已本地安装,AFAIK是一个很好的做法。另外, electron ProjectInitializer__ElectronMain.js 起作用,它可以从我的项目目录中执行此控制台命令。

I got Error: spawn electron ENOENT error. Electron has been installed locally, AFAIK is the good practice. Also, electron ProjectInitializer__ElectronMain.js works, it to execute this console command from my project directory.

经常关注投票 ENOENT错误调试指南,我得到了原因: process.env中没有目录.PATH ,其中包括电子

Following frequently up-voted ENOENT error debugging guidance, I got the cause: there is no directory among process.env.PATH, which includes electron.

我对 PATH 变量了解不多,所以我无法回答此变量中必须包含什么以及什么是不。但是我想问的是:如何执行本地安装(在 node_modules 中)的Node.js应用程序(例如 electron )?

I know about PATH variable not much, so I can not answer what must be in this variable and what is not. But what I want to ask is: how to execute locally installed (in node_modules) Node.js applications (like electron)?

顺便说一句, execa 被称为改进的 child_process 运行电子时没有错误(更新:版本2.xx已经不运行):

By the way, execa which is known as improved child_process runs electron without errors (update: version 2.x.x already do not runs):

import executeExternalCommand, { ExecaReturnValue } from 'execa';

try {
  await executeExternalCommand(
      'electron',
      ['ProjectInitializer__ElectronMain.js'],
      { cwd: __dirname }
  );
} catch (error) {
  console.error(error);
}

以某种方式,要感谢 {cwd:__dirname} execa v 1.xx 知道应该在哪里找到电子。不幸的是, execa 的社区和文档太少,因此停止使用它。

Somehow, thanks to { cwd: __dirname }, the execa v 1.x.x knows, where should to find the electron. Unfortunately, execa has too small community and small documentations, so stopped to use it.

我如何运行具有spawn参数的Node.js脚本

通过命令我创建的我的库初始化

在package.json中:

In package.json:

"bin": {
  "my-library": "bin/my-library"
}

bin / my-library (无文件扩展名)中:

In bin/my-library (no filename extension):

#!/usr/bin/env node

require('../CLI').interpretConsoleCommandAndExecute(process.argv);

CLI.js 中,我解析控制台命令,如果它是 my-library init ,我将尝试执行

In CLI.js I parse the console command, and if it is the my-library init, I'll try to execute

const childProcess: ChildProcess__type = ChildProcess.spawn(
   'electron',
   [ 'ProjectInitializer__ElectronMain.js' ],
   { cwd: __dirname }
);

console.log(process.env)输出

下面的输出用于PhpStorm内置控制台,但是在其他控制台中,例如。 G。在cmder中,输出是不同的。

Below output is for PhpStorm build-in console, however in other consoles, e. g. in cmder, output is different.

{ FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
  CommonProgramFiles: 'C:\\Program Files\\Common Files',
  PROMPT: '$P$G',
  SESSIONNAME: 'Console',
  COMPUTERNAME: 'MSI',
  OneDriveConsumer: 'D:\\OneDrive',
  __INTELLIJ_COMMAND_HISTFILE__:
   'C:\\Users\\i\\.PhpStorm2019.1\\config\\terminal\\history\\history-34',
  SystemDrive: 'C:',
  NUMBER_OF_PROCESSORS: '12',
  LOGONSERVER: '\\\\MSI',
  TEMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
  TMP: 'C:\\Users\\i\\AppData\\Local\\Temp',
  HOMEPATH: '\\Users\\i',
  PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JSE;.WSF;.WSH;.MSC',
  USERNAME: 'i',
  ProgramFiles: 'C:\\Program Files',
  USERDOMAIN_ROAMINGPROFILE: 'MSI',
  LOCALAPPDATA: 'C:\\Users\\i\\AppData\\Local',
  TERMINAL_EMULATOR: 'JetBrains-JediTerm',
  PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 158 Stepping 10, GenuineIntel',
  DriverData: 'C:\\Windows\\System32\\Drivers\\DriverData',
  APPDATA: 'C:\\Users\\i\\AppData\\Roaming',
  ALLUSERSPROFILE: 'C:\\ProgramData',
  USERDOMAIN: 'MSI',
  OS: 'Windows_NT',
  PROCESSOR_LEVEL: '6',
  ProgramData: 'C:\\ProgramData',
  ComSpec: 'C:\\Windows\\system32\\cmd.exe',
  PROCESSOR_ARCHITECTURE: 'AMD64',
  FPS_BROWSER_USER_PROFILE_STRING: 'Default',
  SystemRoot: 'C:\\Windows',
  PROCESSOR_REVISION: '9e0a',
  OneDrive: 'D:\\OneDrive',
  PSModulePath:
   'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules',
  PATH:
   'D:\\PhpStorm\\InHouseDevelopment\\my-library\\node_modules\\.bin;C:\\ProgramData\\DockerDesktop\\version-bin;C:\\Program Files\\Docker\\Docker\\Resources\\bin;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Program Files
\\Intel\\Intel(R) Management Engine Components\\iCLS\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Pro
gram Files\\Intel\\WiFi\\bin\\;C:\\Program Files\\Common Files\\Intel\\WirelessCommon\\;C:\\Program Files (x86)\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\DAL;C:\\Program Files (x86)\\Intel\\I
ntel(R) Management Engine Components\\IPT;C:\\Program Files\\Intel\\Intel(R) Management Engine Components\\IPT;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile\\;C:\\Program Files (x86)\\Common Files\\Acronis\\VirtualFile64\\;C:\\Program Files (x86)\\Com
mon Files\\Acronis\\FileProtector\\;C:\\Program Files (x86)\\Common Files\\Acronis\\FileProtector64\\;C:\\Program Files (x86)\\Common Files\\Acronis\\SnapAPI\\;C:\\Program Files\\nodejs\\;C:\\Program Files\\Git\\cmd;C:\\Program Files (x86)\\Yarn\\bin\\;C:\\Users\\t
okug\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\i\\AppData\\Roaming\\npm;C:\\Users\\i\\AppData\\Local\\Yarn\\bin;C:\\texlive\\2019\\bin\\win32',
  'ProgramFiles(x86)': 'C:\\Program Files (x86)',
  USERPROFILE: 'C:\\Users\\i',
  windir: 'C:\\Windows',
  ProgramW6432: 'C:\\Program Files',
  configsetroot: 'C:\\Windows\\ConfigSetRoot',
  'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
  PUBLIC: 'C:\\Users\\Public',
  HOMEDRIVE: 'C:',
  CommonProgramW6432: 'C:\\Program Files\\Common Files' }

尝试执行ChildProcess.spawn('env')

在Php Strorm控制台中,它会导致出现常见的错误:spawn env ENOENT

In Php Strorm console, it causes familiar Error: spawn env ENOENT.

推荐答案

如聊天中所讨论的,您收到的错误通常是由您试图运行的可执行文件引起的不可用

As discussed in the chat, the error you are getting is usually caused by the fact that the executable you are trying to run is not available

现在有多种原因可能导致可执行文件不可用

Now there are multiple reasons the executable may not be available


  1. 可执行文件根本不在系统上任何地方

  2. 可执行文件在那里,但不在系统的 PATH 变量定义的文件夹中

  3. 可执行文件在当前目录中,但是正在运行进程的目录上下文不同

  1. The executable is not there at all anywhere on the system
  2. The executable is there but not in the folders defined by system's PATH variable
  3. The executable is there in the current directory but the directory context in which the process is being run is different

要修复#1 #2 ,只需在系统PATH中全局安装可执行文件即可。

To fix #1 and #2 you just install the executable globally in system PATH

要修复#3 ,您可以做两件事。添加当前目录的路径( {cwd:__dirname} )以及可执行文件的相对路径

For fixing #3 you can do two things. Add the path for the current directory ({ cwd: __dirname}) and also a relative path to executable

const childProcess: ChildProcess__type = ChildProcess.spawn( 
Path.resolve(__dirname, 'node_modules/.bin/electron'), 
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ], 
{ cwd: __dirname} 
); 

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'./node_modules/.bin/electron'), 
[ Path.resolve(__dirname, 'ProjectInitializer__ElectronMain.js') ], 
{ cwd: __dirname} 
); 

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'node_modules/.bin/electron', 
[ './ProjectInitializer__ElectronMain.js' ], 
{ cwd: __dirname} 
); 

如果您决定覆盖 PATH 环境变量,您可以通过传递带有更多值的 env 参数

In case you decide to override the PATH environment variable you can do it passing the env parameters with more values

const childProcess: ChildProcess__type = ChildProcess.spawn( 
'node_modules/.bin/electron', 
[ './ProjectInitializer__ElectronMain.js' ], 
{ cwd: __dirname, env: {....}} 
); 

您可以使用 process.env ,然后进行更新,并将其传递给 env 参数

You can use the existing environment variables from process.env and then update the same, and pass it to env parameter

这篇关于如何通过child_process.spawn()执行本地安装的Node.js应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆