How to run a batch file in Node.js with input and get an output ?
Last Updated :
02 Aug, 2024
In this article, we are going to see how can you run a batch file with input and get an output file in Node.js. A batch file is a script file that stores command to be executed in a serial order.
Node.js is asynchronous in nature, it doesn't wait for the batch file to finish its execution. Instead, it calls functions that define when the batch file is executed, and hence it tries to print the data even when it does not fetch yet.
Solution: The solution is to use a Node.js module named Child Process. Child Process contains a method 'spawn' that spawns the child process asynchronously, without blocking the Node.js.
Let's see the complete process step-by-step.
Step 1: Create a folder, inside this folder create the app.js file, input.txt file, and bash.sh file. Inside input.txt file and bash.sh file write the code given below.
input.txt
Hello Geeks!
bash.sh
#!/bin/bash
input=`cat -`
echo "Input: $input"
Step 2: Locate this folder into the terminal & type the command
npm init -y
It initializes our node.js application.
Step 3: Install Child Process modules inside the project using the following command
node install child_process
Step 4: Inside the 'app.js' file, require the Child Process module, and create a constant 'bash_run' for executing the bash file.
const childProcess = require("child_process");
const bash_run = childProcess.spawn(
'/bin/bash',["test.sh"],{env: process.env});
Step 5: Now, let's use the 'stdout' method to print the result and 'stderr' to print the error.
bash_run.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
bash_run.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
Step 6: Now, use File System Module to create Read and Write Stream for Input and Output files respectively. After that, we will send the get result of the input text file to the output text file using the bash_run method we created earlier.
const fs = require("fs");
const input = fs.createReadStream("input.txt");
const output = fs.createWriteStream("output.txt");
bash_run.stdout.pipe(output);
input.pipe(bash_run.stdin);
Complete Code:
app.js
const childProcess = require("child_process");
const bash_run = childProcess.spawn('/bin/bash',
["bash.sh"], { env: process.env });
bash_run.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
bash_run.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
const fs = require("fs");
const output = fs.createWriteStream("output.txt");
const input = fs.createReadStream("input.txt");
bash_run.stdout.pipe(output);
input.pipe(bash_run.stdin);
Step to run the application: Open the terminal and type the following command.
node app.js
Output:
Similar Reads
How to return an array of lines from a file in node.js ? In this article, we will return an array of lines from a specified file using node.js. The fs module is used to deal with the file system in node.js and to read file data we use fs.readFileSync( ) or fs.readFile( ) methods. Here we will use the readFileSync method to read the file, and we use the st
2 min read
How to Create and Run a Node.js Project in VS Code Editor ? Visual Studio Code (VS Code) is a powerful and user-friendly code editor that is widely used for web development. It comes with features like syntax highlighting, code suggestions, and extensions that make coding easier. In this article, we'll show you how to quickly create and run a Node.js project
2 min read
How to read and write files in Node JS ? NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to Push Data to Array Asynchronously & Save It in Node.js ? Node.js is a powerful environment for building scalable and efficient applications, and handling asynchronous operations is a key part of its design. A common requirement is to collect data asynchronously and store it in an array, followed by saving this data persistently, for instance, in a databas
7 min read
How to Convert an Existing Callback to a Promise in Node.js ? Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
7 min read
How to Run a Database Query in a JS File? To run a database query in a JavaScript file, you typically use a Node.js environment along with a library or package that can communicate with your database. Hereâs a basic example of how to set up and run a database query using Node.js and a popular database library, such as mysql2 for MySQL or pg
3 min read
How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How can We Run an External Process with Node.js ? Running external processes from within a Node.js application is a common task that allows you to execute system commands, scripts, or other applications. Node.js provides several built-in modules for this purpose, including child_process, which allows you to spawn, fork, and execute processes. This
4 min read
How to Create a Pre-Filled forms in Node.js ? Pre-Filled forms are those forms that are already filled with desired data. These are helpful when a user wants to update something like his profile, etc. We just create a folder and add a file, for example, index.js. To run this file you need to run the following command. node index.js Filename: Sa
2 min read
How to work with Node.js and JSON file ? Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 min read