How To Execute Shell Commands with JS
Author: Doe Hoon LEE
As you may know, I am a JavaScript lover π
I would like to do anything with JavaScript π
Anyway, I had to run shell commands for one of my projects and thought βCan I do this with JavaScript? hmm..?β
Then, of course, I googled LOL and not so surprisingly, the answer was π YES.
It does require
something though.
So we will first have to write this
const { exec } = require('child_process');
Hmm.. what should we do then?
How about we follow the tradition and print Hello World
π€£
const { exec } = require('child_process');
exec(`echo 'Hello World'`, (err, stdout) => {
if (err) console.log(err);
console.log(stdout)
})
Yay!
Oh, wait a second..
Do you remember this How To Open Everything on Terminal (1) post?
Can we do this on JavaScript too?
const { exec } = require('child_process');
const folderPath = '/Users/doehoonlee/Desktop/sample'
exec(`open ${folderPath}`, (err, stdout) => {
if (err) console.log(err);
console.log(stdout)
})
Can we store something we got from executing a command?
const { exec } = require('child_process');
const info = {
pwd: '',
currentTime: '',
}
exec(`pwd`, (err, stdout) => {
if (err) console.log(err);
info.pwd = stdout;
console.log('pwd stored..!')
});
exec(`date`, (err, stdout) => {
if (err) console.log(err);
info.currentTime = stdout;
console.log('Current Time stored..!')
console.log(info)
})
Wallah!!
See you again!
Leave a comment