首页 > 解决方案 > 如何在 TS 中运行命令?

问题描述

我试图从 TS 运行命令

function executeCommand(command : string, callback: (error: ExecException, stdout : string, stderr : string) => void): void  {
    const path= path.join(vscode.workspace.rootPath,"products");

    exec(command, {cwd: '${path}'}, callback);
}

       const command = ({
            'darwin': ``,
            'linux': `cf env`,
            'win32': `cf env`
        } as any)[platform];


 executeCommand(command, (error, stdout, stderr) => {
            if (error) {
                console.warn(error);
            }
      ...
 }

我想cf env在不同的路径上运行命令,所以我尝试更改 cwd

当我这样做时,我得到了一个错误:

生成 C:\WINDOWS\system32\cmd。

当我删除 cwd 然后它工作但我需要使用“CWD”选项

标签: javascriptnode.jstypescript

解决方案


您所做的是尝试将路径设置为文字字符串:${path}

要使用字符串插值,您必须使用反引号而不是单引号,如下所示:

`${path}` // resolves to the path

但由于您没有对任何东西使用插值,您可以直接将路径放入函数中:

exec(command, {cwd: path}, callback);

您遇到的错误是因为路径${path}无效,cmd 没有启动。


推荐阅读