0
0
Node.jsframework~5 mins

exec for running shell commands in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the exec function in Node.js?
The exec function runs shell commands from a Node.js script, letting you execute system commands and get their output.
Click to reveal answer
beginner
Which Node.js module provides the exec function?
The child_process module provides the exec function to run shell commands.
Click to reveal answer
intermediate
What are the three main arguments of exec(command, options, callback)?
1. command: The shell command string to run.<br>2. options: Optional settings like environment variables.<br>3. callback: Function called with error, stdout, and stderr after command finishes.
Click to reveal answer
intermediate
How do you handle errors when using exec?
Check if the error argument in the callback is set. If yes, the command failed or had issues. You can then handle or log the error.
Click to reveal answer
beginner
What is a simple example of using exec to list files in the current directory?
const { exec } = require('child_process');
exec('ls', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Files:\n${stdout}`);
});
Click to reveal answer
Which module must you import to use exec in Node.js?
Ahttp
Bfs
Cos
Dchild_process
What does the exec callback receive as arguments?
Aerror, stdout, stderr
Bstdout, stderr, error
Ccommand, options, callback
Dinput, output, error
If a shell command run by exec fails, where will the error info appear?
AIn the <code>error</code> argument of the callback
BIn the <code>stdout</code> argument
CIn the <code>options</code> argument
DIn the <code>command</code> string
Which of these is a correct way to run the pwd command using exec?
Aexec('pwd', (stdout, stderr) => { console.log(stdout); });
Bexec('pwd', (err) => { console.log(err); });
Cexec('pwd', (err, stdout) => { console.log(stdout); });
Dexec('pwd', (error, output) => { console.log(output); });
What is a common use case for exec in Node.js?
AManipulating arrays
BRunning system shell commands and getting their output
CCreating HTTP servers
DReading files from disk
Explain how to use exec to run a shell command and handle its output and errors.
Think about the three arguments in the callback and how to safely use them.
You got /5 concepts.
    Describe a simple example where exec is used to list files in a directory and print them.
    Remember the common 'ls' command and how to handle callback arguments.
    You got /4 concepts.