That should be fine.
The module 'util' is to promisify exec(), for it to return a promise, then you await it, and can use it.
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const main = async() => {
const { stdout, stderr } = await exec('ls', ['a', '-l' ])
if (stderr) {
console.log(stderr)
}
console.log(`the list of files in this directory is: ${stdout}`)
}
main()
exec (spawn and fork as well) are fork process (child process) from the main node process (mother process), means that they run on a concurrent process, detached from the mother one. It's very efficient as they use another thread of the processor.
In the case of exec, it open a new terminal (tty) and run on it, so the command exec('ls', ['a','-l'}) is running 'ls -l' cmd in a shell (i don t know why the 'a'). Because this exec child-process is running into a shell, any shell command can be executed: I could have done await exec('find . -type f | wc -l')
return the number of files, or await exec('cat fileName.js')
(print out the content of fileName in the terminal) return the content of fileName.js into stdout.
Exec return a call-back with (err, stdout, stderr), for this snippet to be more clear, here util.promisify()
promisify the call-back and then we can use async/await or .then().catch().
We also could have done:
const util = require('util')
const { exec } = require('child_process')
const ex = util.promisify(exec)
const main = async() => {
const { stdout, stderr } = await ex('ls')
if (stderr)...
In fact more basically this code could be written like this
const { exec } = require('child_process');
exec('ls', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
See the nodejs doc https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
hope it helps