How to run a batch file in Node.js using input and get output

In perl , if you need to run a batch file, this can be done using the following instructions.

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

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

I like to know if this can be done in Node.js or not. If so, how?

+5
source share
1 answer

You will need to create a child process. Unline Python, node.js is asynchronous, which means that it does not wait for script.bat complete. Instead, it calls functions that 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 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); }); 

In addition to assigning events to a process, you can connect stdin and stdout threads to other threads. 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 test.sh bash script test.sh :

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

And test input text input.txt :

 Hello world. 

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

 stdout: Input: Hello world. child process exited with code 0 

And this is in output.txt :

 Input: Hello world. 

The procedure in the windows will be similar, I just think you can directly invoke the batch file:

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

Source: https://habr.com/ru/post/1233591/


All Articles