Run Commands In Node.js
Command-ception!
October 17, 2020
After a very intense and stressful six months, I finally got a short and temporary breather where things are back to normal. And by normal, I mean waking up 10am on a Saturday, hopping on to my trusty PC, and writing hobby code. That's right, that's what I do on my weekends besides sleeping and watching YouTube all day.
Anwyays, for this little project of mine, I wanted to have a Node.js script run another Node.js script. This will come in handy later on at work, because we've been planning to port over some of our internal tooling to Node.js. Part of the work these tools do is orchestrate calls to several other tools.
Without further ado, the really short snippet that allows me to run external commands from within node is:
spawnSync('command', ['pathToModule.js'], {
cwd: moduleDir,
stdio: ['pipe', process.stdout, process.stderr]
})
Let me break it down for you:
- The first argument,
command
, is the command to run. - The second argument is an array of arguments to pass to the command.
cwd
the path the command runs relative to.stdio
is the configuration of the the I/O to and from the command.stdin
is set topipe
because I'm not piping inputs to the command.stdout
is set to the parent'sstdout
so I can see log messages.stderr
is set to the parent'sstdout
so I can see error messages.
I'm using spawnSync
. the synchronous version of spawn
, because synchronous code is easier to write and understand. Besides, I'm not running it concurrently with something else, making the whole async thing an unnecessary overhead... for now.
So there you have it, the short snippet that allows you to run other commands from Node.js. There are other commands like exec
, execFile
, and fork
that do a similar job with minor differences which may better fit other uses cases. But for now, spawnSync
is what I need.