Node.js 如何使用节点JS子进程Exec在Windows上触发错误

Node.js 如何使用节点JS子进程Exec在Windows上触发错误,node.js,windows,batch-file,child-process,windows-console,Node.js,Windows,Batch File,Child Process,Windows Console,我正在构建一个跨平台节点实用程序来读取文件系统(设备、分区)的详细信息,在我的测试中,我需要测试该实用程序运行以获取其数据的shell命令引发错误时的行为 不幸的是,我对dos或PowerShell知之甚少,我不知道如何编写一个批处理命令,该命令会抛出错误并带着错误退出 如何在批处理中抛出错误,以便子进程能够捕获它 下面是供您处理的示例代码: import os from 'os'; import child from 'child_process'; import { expect } fro

我正在构建一个跨平台节点实用程序来读取文件系统(设备、分区)的详细信息,在我的测试中,我需要测试该实用程序运行以获取其数据的shell命令引发错误时的行为

不幸的是,我对dos或PowerShell知之甚少,我不知道如何编写一个批处理命令,该命令会抛出错误并带着错误退出

如何在批处理中抛出错误,以便子进程能够捕获它

下面是供您处理的示例代码:

import os from 'os';
import child from 'child_process';
import { expect } from 'chai';

const cmd = os.platform() === 'win32'
   // This command should result in throwing an error to exec
   ? `1>&2 echo 'Echoed Error'\nexit /b 1`
   // This has the expected behaviour on linux and osx
   : `>&2 echo 'Echoed Error'; exit 1`; 

expect(child.execSync.bind(child, cmd)).to.throw();
child.exec(cmd, (err) => {
  expect(err).to.be.an.instanceof(Error);
});

我发现了一种在cmd中导致错误的方法,即调用不存在的外部或内部命令。因此,像
error
iamnotanexistingcommand
这样的命令将抛出一个错误,这对于我试图重现的内容来说已经足够了。

请查看并发布一个。是的,您似乎已经足够长时间知道如何发布问题了。谢谢您的评论:)我没想到这是必要的。我认为行
1>&2 echo'echomed Error'\nexit/b 1
就足够了。你现在应该找到你想要的