需要使用TypeScript、SystemJS和Electron的nodejs“child_process”

tvz2xvvm  于 2023-06-20  发布在  Electron
关注(0)|答案(4)|浏览(161)

我正在做一个简单的nodejs electron(以前称为atom shell)项目。我使用angular 2编写它,使用与typescript文档中推荐的项目设置相同的项目设置:
tsc:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
  "node_modules",
  "typings/main",
  "typings/main.d.ts"
  ]
}

我需要运行一个命令,我发现我可以用节点“child_process”来完成。我无法找到任何方法来“导入”或“要求”它,同时从node.d.ts文件使用其类型。我在node.d.ts文件中找到了符合我需要的“child_process”接口,这是它在node.d.ts文件中的外观:

declare module "child_process" {
    import * as events from "events";
    import * as stream from "stream";

    export interface ChildProcess extends events.EventEmitter {
        stdin:  stream.Writable;
        stdout: stream.Readable;
        stderr: stream.Readable;
        pid: number;
        kill(signal?: string): void;
        send(message: any, sendHandle?: any): void;
        disconnect(): void;
        unref(): void;
    }

    export function spawn(command: string, args?: string[], options?: {
        cwd?: string;
        stdio?: any;
        custom?: any;
        env?: any;
        detached?: boolean;
    }): ChildProcess;
    export function exec(command: string, options: {
        cwd?: string;
        stdio?: any;
        customFds?: any;
        env?: any;
        encoding?: string;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function exec(command: string, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string,
        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string, args?: string[],
        callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function execFile(file: string, args?: string[], options?: {
        cwd?: string;
        stdio?: any;
        customFds?: any;
        env?: any;
        encoding?: string;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
    }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;
    export function fork(modulePath: string, args?: string[], options?: {
        cwd?: string;
        env?: any;
        execPath?: string;
        execArgv?: string[];
        silent?: boolean;
        uid?: number;
        gid?: number;
    }): ChildProcess;
    export function spawnSync(command: string, args?: string[], options?: {
        cwd?: string;
        input?: string | Buffer;
        stdio?: any;
        env?: any;
        uid?: number;
        gid?: number;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
        encoding?: string;
    }): {
        pid: number;
        output: string[];
        stdout: string | Buffer;
        stderr: string | Buffer;
        status: number;
        signal: string;
        error: Error;
    };
    export function execSync(command: string, options?: {
        cwd?: string;
        input?: string|Buffer;
        stdio?: any;
        env?: any;
        uid?: number;
        gid?: number;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
        encoding?: string;
    }): string | Buffer;
    export function execFileSync(command: string, args?: string[], options?: {
        cwd?: string;
        input?: string|Buffer;
        stdio?: any;
        env?: any;
        uid?: number;
        gid?: number;
        timeout?: number;
        maxBuffer?: number;
        killSignal?: string;
        encoding?: string;
    }): string | Buffer;
}

但是我只能(据我所知)通过使用import来获得这种类型:

import * as child_process from 'child_process';

唯一的问题是,当我这样做时,我的应用程序无法加载,我在控制台中得到以下错误:

GET file:///C:/angular2Samples/NGW-electron-VS%20-%20TEMP/child_process net::ERR_FILE_NOT_FOUND

现在,我通过使用来获得我的方式:

var child_process = require('child_process');

但是我找不到任何方法来将类型信息添加到这个var中:

var child_process : I_CANT_PUT_ANY_CHILD_PROCESS_TYPE_HERE = require('child_process');

有什么想法可以让我得到child_process(或者任何其他声明的节点模块,它们不是我可以在“:”运算符后声明的公共接口)的类型信息吗?
非常感谢您的帮助和解释:)
更新-------------------------------------------------------------
根据tenbits的建议,我在文件顶部添加了如下引用:///
使用了你说的import statment,但没有改变我的模块加载器。它仍然没有像预期的那样以同样的错误工作。我对改变模块系统感到不舒服,因为我的项目使用angular 2,他们的文档和一些指南说,新项目没有以前的偏好(我对模块加载器场景非常陌生,我还没有完全理解它是如何工作的)。当我试图改变它,我得到了一些错误的Angular 2的东西,我没有足够的时间进入目前。难道不应该有一种不改变模块加载器的方法吗?通过浏览systemjs站点,它在开始时说它支持commonjs模块:Systemjs doc
我真的很想找到一个不改变模块系统的解决方案,或者更深入地解释一下到底发生了什么,以及解决这些模块加载问题的方法。

sg2wtvxw

sg2wtvxw1#

  • 好吧,经过一些研究#L138我已经找到了解决方案 *

您可以像以前一样使用import

import * as child from 'child_process';

var foo: child.ChildProcess = child.exec('foo.sh');
console.log(typeof foo.on);

但是您应该配置SystemJS以将模块Map到NodeJS

System.config({
  map: {
    'child_process': '@node/child_process'
  }
});
  • 就是这样 *
cxfofazt

cxfofazt2#

如果错误消息为**'Cannot find module' child_process 'or its corresponding type declarations',则答案为'npm install@types/watch'**

cetgtptt

cetgtptt3#

对我来说,它与回调一起显示结果。

import * as child from 'child_process';

 var foo: child.ChildProcess = child.exec('dir', (error: string, stdout: string, stderr: string) => {
            console.log(stdout);      
        });

我没有在SystemJS中添加任何Map,因为我在节点应用程序中没有任何这样的配置

7eumitmz

7eumitmz4#

我和Bing聊天:

import { exec } from "child_process";

function openBrowser(url) {
  // Get the operating system
  const os = process.platform;

  // Choose the command based on the operating system
  let cmd;
  if (os === "win32") {
    // Windows
    cmd = `start ${url}`;
  } else if (os === "darwin") {
    // Mac OS
    cmd = `open ${url}`;
  } else if (os === "linux") {
    // Linux
    cmd = `xdg-open ${url}`;
  } else {
    // Unsupported OS
    throw new Error("Unsupported operating system");
  }

  // Execute the command
  exec(cmd, (error, stdout, stderr) => {
    if (error) {
      console.error(`Failed to open browser: ${error.message}`);
      return;
    }
    if (stderr) {
      console.error(`Error: ${stderr}`);
      return;
    }
    console.log(`Opened browser: ${stdout}`);
  });
}

// Example usage
openBrowser("https://www.google.com");

相关问题