如何使用输入在Node.js中运行批处理文件并获取输出

Shv*_*kra 5 javascript windows batch-file node.js

perl如果你需要运行一个批处理文件,它可以通过下面的语句来完成.

system "tagger.bat < input.txt > output.txt";
Run Code Online (Sandbox Code Playgroud)

这里tagger.bat是批处理文件,input.txt是输入文件,output.txt是输出文件.

我想知道是否有可能做到这一点Node.js ?如果有,怎么样?

Tom*_*ica 4

您将需要创建一个子进程。Unline Python、node.js 是异步的,这意味着它不会等待script.bat完成。script.bat相反,它在打印数据或存在时调用您定义的函数:

// Child process is required to spawn any kind of asynchronous process
var childProcess = require("child_process");
// This line initiates bash
var script_process = childProcess.spawn('/bin/bash',["test.sh"],{env: process.env});
// Echoes any command output 
script_process.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});
// Error output
script_process.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});
// Process exit
script_process.on('close', function (code) {
  console.log('child process exited with code ' + code);
});
Run Code Online (Sandbox Code Playgroud)

除了将事件分配给流程之外,您stdin还可以将流连接到stdout其他流。这意味着其他进程、HTTP 连接或文件,如下所示:

// Pipe input and output to files
var fs = require("fs");
var output = fs.createWriteStream("output.txt");
var input =  fs.createReadStream("input.txt");
// Connect process output to file input stream
script_process.stdout.pipe(output);
// Connect data from file to process input
input.pipe(script_process.stdin);
Run Code Online (Sandbox Code Playgroud)

然后我们制作一个测试 bash 脚本test.sh

#!/bin/bash
input=`cat -`
echo "Input: $input"
Run Code Online (Sandbox Code Playgroud)

并测试文本输入input.txt

Hello world.
Run Code Online (Sandbox Code Playgroud)

运行后node test.js我们在控制台中得到:

stdout: Input: Hello world.

child process exited with code 0
Run Code Online (Sandbox Code Playgroud)

这在output.txt

Input: Hello world.
Run Code Online (Sandbox Code Playgroud)

Windows 上的过程类似,我只是认为你可以直接调用批处理文件:

var script_process = childProcess.spawn('test.bat',[],{env: process.env});
Run Code Online (Sandbox Code Playgroud)