Node.js exec
Nodes exec exposes the outside operating systems functions by sending commands to a shell in a separate OS process. When the command completes, the callback is called with the output or error. For these examples, I will just focus on UNIX (OS X, Linux etc) applicable commands since Windows commands are very different. By default exec on UNIX uses SH (/bin/sh specifically).
const exec = require('child_process').exec; // From https://stackoverflow.com/a/13322549 const cmd = "ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'"; exec(cmd, function(err, output, errorOuput) { if (err) { console.log(errorOuput); throw(new Error(err)); } console.info('IP Address:', output); // IP Address: Your computers (or virtual machines) IP address });
Although the command looks complicated, it is much harder to do in Node.js: https://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js, at least without a library. Basically, almost any command that can be run in your command line can run unmodified in exec. exec also has an options argument which supports concepts like environment variables. For example to check the installed Node.js versions via NVM:
exec('. "$NVM_DIR/nvm.sh" && nvm ls', { // $HOME is a default environment variable that will point to the current users Home directory NVM_DIR: '$HOME/.nvm' }, function(err, output, errorOuput) { if (err) { console.log(errorOuput); throw(new Error(err)); } console.info('Installed Node.js versions:\n', output); // Installed Node.js versions: // (Your Node.js versions installed with NVM) });
More info on execs details can be found here.
exec is great for short running scripts and simple commands, but can be bad for long processes since it only outputs all the results at the end. Additionally, exec does no checks, so all external input needs to be sanitized to ensure it does not contain descructive commands which makes complex script executions cumbersome.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/nodeExec.js












