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?✗ Incorrect
The
exec function is part of the child_process module.What does the
exec callback receive as arguments?✗ Incorrect
The callback receives
error, stdout, and stderr in that order.If a shell command run by
exec fails, where will the error info appear?✗ Incorrect
Errors are passed as the first argument
error in the callback.Which of these is a correct way to run the
pwd command using exec?✗ Incorrect
The callback receives error first, then stdout. Option C uses correct argument order.
What is a common use case for
exec in Node.js?✗ Incorrect
exec is used to run shell commands and capture their output.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.