Running shell commands in your node application:
Found great explanation here,
The Child Process Module
When we execute shell commands, we are running code outside of our Node.js application. In order to do this, we need to run these commands in a child process.
A child process is code that is run in a different thread (and process id) outside your Node.js application. However, we can still send and receive information from the child process using standard I/O streams.
In Node.js, we can use the child_process
standard library to start these processes to run shell commands.
Running Basic Shell Commands#
To run a simple command and read its output, we can use the exec
function.
In this example, let’s list the files in our current directory using ls
, and print the output from our Node.js code:
const { exec } = require('node:child_process')
// run the `ls` command using exec
exec('ls ./', (err, output) => {
// once the command has completed, the callback function is called
if (err) {
// log and return if we encounter an error
console.error("could not execute command: ", err)
return
}
// log the output received from the command
console.log("Output: \n", output)
})
Note
When we run
exec
, our application spawns a shell ('/bin/sh'
by default) and runs the given command on that shell. This means that the command is first processed by the shell and then executed. So for example, when we runls ./*.md
, the shell processes./*.md
intoREADME.md
and then runs the commandls README.md
:
We are also limited to 1MB by default as the maximum size of output generated by the command.
Executing Long Running Commands
The previous example executed the ls
command that returned its output immediately. What about commands whose output is continuous, or takes a long time to retrieve?
For example, when we run the ping
command, we get continuous output at periodic intervals:
➜ ~ ping google.com
PING google.com (142.250.77.110): 56 data bytes
64 bytes from 142.250.77.110: icmp_seq=0 ttl=116 time=11.397 ms
64 bytes from 142.250.77.110: icmp_seq=1 ttl=116 time=17.646 ms ## this is received after 1 second
64 bytes from 142.250.77.110: icmp_seq=2 ttl=116 time=10.036 ms ## this is received after 2 seconds
64 bytes from 142.250.77.110: icmp_seq=3 ttl=116 time=9.656 ms ## and so on
# ...
More in the article. Check it (link at start)