node: executing shell commands in a node script

2021-09-11

 | 

~1 min read

 | 

181 words

I’ve been working on some automation and have been using a Node script to help with that.

I like Node, but there are certain things where it makes more sense to reach for Bash, for example, if I want to run a git command or npm.

Node enables this with the child_process module which spawns subprocesses.

Let’s look at an example of how you could run a bash command inside a Node script:

script.js
#!/usr/bin/env node
const { spawn } = require("child_process")

const ls = spawn("ls", ["-la"])

ls.stdout.on("data", (data) => {
  console.log(`stdout: ${data}`)
})

ls.stderr.on("data", (data) => {
  console.error(`stderr: ${data}`)
})

ls.on("close", (code) => {
  console.log(`child process exited with code ${code}`)
})

In the above example, we have spawn a subprocess which then runs ls with the options of -l and -a.

This is equivalent (though more verbose) as running the command in your terminal:

% ls -la

The same thing can be done for git:

const git = spawn("git", ["status"])

Resources:


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!