running shell commands javascript 1

running shell commands javascript

const execSync = require('child_process').execSync;
// import { execSync } from 'child_process';  // replace ^ if using ES modules

const output = execSync('ls', { encoding: 'utf-8' });  // the default is 'buffer'
console.log('Output was:\n', output);

Here is what the above code is Doing:
1. We’re requiring the child_process module.
2. We’re calling the execSync() function, which is a synchronous version of exec().
3. We’re passing the command we want to run as the first argument.
4. We’re passing an options object as the second argument.
5. We’re setting the encoding option to ‘utf-8’.
6. We’re logging the output of the command to the console.

Similar Posts