Node.js - Native operating system commands using child_process

by
Jeremy Canfield |
Updated: November 25 2024
| Node.js articles
child_process can be used to run a command on the same system as your Node.js program. Here is the minimal boilerplate code without any error handling to list the files in the /tmp directory on the same system as your Node.js program.
import { exec as execCb } from "node:child_process";
import { promisify } from "node:util";
const exec = promisify(execCb);
const { error, stdout, stderr } = await exec("ls");
const lines = []
if (stdout) {
const x = stdout.split('\n')
x.forEach(line => {
if (line != "") {
lines.push(line)
}
})
}
if (stderr) {
console.log(`${new Date()} : STDERR => ${stderr}`)
}
console.log(lines)
process.exit()
Did you find this article helpful?
If so, consider buying me a coffee over at