In a node.js, I'd like to find a way to obtain the output of a Unix terminal command. Is there any way to do this?
function getCommandOutput(commandString){
// now how can I implement this function?
// getCommandOutput("ls") should print the terminal output of the shell command "ls"
}
Thats the way I do it in a project I am working now.
Example: Retrieving git user
You're looking for child_process
As pointed out by Renato, there are some synchronous exec packages out there now too, see sync-exec that might be more what yo're looking for. Keep in mind though, node.js is designed to be a single threaded high performance network server, so if that's what you're looking to use it for, stay away from sync-exec kinda stuff unless you're only using it during startup or something.
If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's
promisify
function withasync / await
to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:This also has the added benefit of returning a rejected promise on failed commands, which can be handled with
try / catch
inside the async code.Thanks to Renato answer, I have created a really basic example: