Skip to content

Instantly share code, notes, and snippets.

@harrypujols
Created May 9, 2017 19:48
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save harrypujols/2a6da11afbd9ee1bef92ddd3402a2fc4 to your computer and use it in GitHub Desktop.
Save harrypujols/2a6da11afbd9ee1bef92ddd3402a2fc4 to your computer and use it in GitHub Desktop.
Execute shell command in javascript
#!/usr/bin/env node
function execute(command) {
const exec = require('child_process').exec
exec(command, (err, stdout, stderr) => {
process.stdout.write(stdout)
})
}
execute('echo "Hello World!"')
@saipranavaddanki02
Copy link

can i also run node js command in this way?

@edwinHernandezB
Copy link

@saipranavaddanki02 if you mean to use that function to execute "node file.js", yes. Remember the root permissions if you're in a Linux distribution, otherwise it wouldn't work

@AmitKulkarni9
Copy link

Does this function work in different OS - Windows, MacOS, Linux ?

@harrypujols
Copy link
Author

Does this function work in different OS - Windows, MacOS, Linux ?

@AmitKulkarni9 as long as the shell has node installed and the file is marked as executable (Windows will ignore the shebang line). The command in the example is a Bash command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment