Bootstrap FreeKB - Node.js - Native operating system commands using child_process
Node.js - Native operating system commands using child_process

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 7c59cb in the box below so that we can be sure you are a human.