admin管理员组

文章数量:1429482

In perl if you need to run a batch file it can be done by following statement.

system "tagger.bat < input.txt > output.txt";

Here, tagger.bat is a batch file, input.txt is the input file and output.txt is the output file.

I like to know whether it is possible to do it be done in Node.js or not? If yes, how?

In perl if you need to run a batch file it can be done by following statement.

system "tagger.bat < input.txt > output.txt";

Here, tagger.bat is a batch file, input.txt is the input file and output.txt is the output file.

I like to know whether it is possible to do it be done in Node.js or not? If yes, how?

Share Improve this question edited Oct 13, 2015 at 8:49 aschipfl 35.1k12 gold badges59 silver badges105 bronze badges asked Oct 13, 2015 at 8:35 Shvet ChakraShvet Chakra 1,04310 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You will need to create a child process. Unline Python, node.js is asynchronous meaning it doesn't wait on the script.bat to finish. Instead, it calls functions you define when script.bat prints data or exists:

// 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 mand 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);
});

Apart from assigning events to the process, you can connect streams stdin and stdout to other streams. This means other processes, HTTP connections or files, as shown below:

// 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);

Then we just make a test bash script test.sh:

#!/bin/bash
input=`cat -`
echo "Input: $input"

And test text input input.txt:

Hello world.

After running the node test.js we get this in console:

stdout: Input: Hello world.

child process exited with code 0

And this in output.txt:

Input: Hello world.

Procedure on windows will be similar, I just think you can call batch file directly:

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

本文标签: javascripthow to run a batch file in Nodejs with input and get an outputStack Overflow