I need to execute a bash script from nodejs app. Usually I would do something like this:
var childProcess = require('child_process');
childProcess.execFile('./test.sh', function (error, stdout, stderr) {
console.log(error, stdout, stderr);
})
But I recently ran into a bash script that never terminated when it was executed like that. This is a minimal example that reproduces the issue:
#!/bin/bash
LC_CTYPE=C cat /dev/urandom | tr -dc "a-zA-Z0-9" | fold -w 8 | head -n 1
LC_CTYPE=C- force thetrto interpret everything as ascii characterstr -dc "a-zA-Z0-9" < /dev/urandom- read pseudorandom bytes, discard everything excepta-zA-Z0-9fold -w 8- wrap output into lines 8 characters longhead -n 1- read the first line (8 characters)
When executed from terminal it works fine and it terminates immediately:
# ./test.sh
0J5hsGeh
When executed using the above nodejs script it just hangs:
# node test.js
It seems that the head -n 1 already terminated but the cat /dev/urandom is still running.
Question: How to execute the script from nodejs so that it does not hang?
Env:
- OS:
Ubuntu 16.04 - Nodejs version:
v6.11.2

exitcommand to the end of your bash scriptexitat the end of the script does nothing and in this case it is not even executed because the previous line never terminates. The-xdoes not help either because the script never finishes so the output generated by-xis not printed. Anyways, I am not trying to debug the bash script. I am trying to find out why executing it through nodejs makes a difference.