Bird
Raised Fist0
Node.jsframework~20 mins

exec for running shell commands in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Exec Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1:30remaining
Output of exec with simple command
What will be the output of this Node.js code using exec to run a shell command?
Node.js
import { exec } from 'child_process';

exec('echo Hello World', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Output: ${stdout.trim()}`);
});
AOutput: Hello World
BError: Command not found
COutput: echo Hello World
DStderr: Hello World
Attempts:
2 left
💡 Hint
Remember that exec runs the command and returns its output in stdout.
Predict Output
intermediate
1:30remaining
Handling errors in exec callback
What will this code print if the command does not exist?
Node.js
import { exec } from 'child_process';

exec('nonexistentcommand', (error, stdout, stderr) => {
  if (error) {
    console.log(`Error: ${error.message}`);
    return;
  }
  console.log(`Output: ${stdout}`);
});
AOutput: nonexistentcommand
BError: Command failed: nonexistentcommand
CError: spawn nonexistentcommand ENOENT
DOutput:
Attempts:
2 left
💡 Hint
If the command is not found, exec returns an error with a message about failure.
component_behavior
advanced
2:00remaining
Behavior of exec with large output
What happens if you run exec with a command that produces a very large output exceeding the default buffer size?
Node.js
import { exec } from 'child_process';

exec('yes | head -n 1000000', (error, stdout, stderr) => {
  if (error) {
    console.log(`Error: ${error.message}`);
    return;
  }
  console.log(`Output length: ${stdout.length}`);
});
AError: stdout maxBuffer exceeded
BNo output and no error
COutput length: 0
DOutput length: 100000
Attempts:
2 left
💡 Hint
exec has a default maxBuffer size for stdout and stderr.
📝 Syntax
advanced
1:30remaining
Correct syntax for exec import and usage
Which option shows the correct modern syntax to import and use exec from 'child_process' in Node.js ES modules?
A
import exec from 'child_process';
exec('ls', (err, stdout) => { console.log(stdout); });
B
const { exec } = require('child_process');
exec('ls', (err, stdout) => { console.log(stdout); });
C
import { exec } from 'child_process';
exec('ls').then(output => console.log(output));
D
import { exec } from 'child_process';
exec('ls', (err, stdout) => { console.log(stdout); });
Attempts:
2 left
💡 Hint
Node.js ES modules use import syntax with curly braces for named exports.
🔧 Debug
expert
2:00remaining
Why does this exec code not print output?
Consider this code snippet: import { exec } from 'child_process'; const result = exec('echo test'); console.log(result.stdout); Why does this code not print 'test'?
Node.js
import { exec } from 'child_process';

const result = exec('echo test');
console.log(result.stdout);
ABecause the command 'echo test' failed to run.
BBecause stdout is only available after the process exits, so result.stdout is undefined immediately.
CBecause exec returns a ChildProcess object, not the command output synchronously.
DBecause exec requires a callback to capture output, otherwise stdout is null.
Attempts:
2 left
💡 Hint
Check what exec returns and how output is accessed.

Practice

(1/5)
1. What does the exec function in Node.js primarily do?
easy
A. Runs shell commands from within a Node.js program
B. Creates a new HTTP server
C. Reads files from the filesystem
D. Starts a database connection

Solution

  1. Step 1: Understand the purpose of exec

    The exec function is designed to run shell commands from Node.js code.
  2. Step 2: Compare with other options

    Creating servers, reading files, or database connections are unrelated to exec.
  3. Final Answer:

    Runs shell commands from within a Node.js program -> Option A
  4. Quick Check:

    exec runs shell commands = B [OK]
Hint: Remember exec runs shell commands, not servers or files [OK]
Common Mistakes:
  • Confusing exec with file reading functions
  • Thinking exec creates servers
  • Assuming exec manages databases
2. Which is the correct way to import and use exec from the child_process module in Node.js?
easy
A. import exec from 'child_process';
B. const exec = require('child_process').exec;
C. const exec = require('exec');
D. import { exec } from 'child_process';

Solution

  1. Step 1: Recall Node.js import syntax for exec

    In Node.js CommonJS, exec is imported as const exec = require('child_process').exec;.
  2. Step 2: Check other options for correctness

    import exec from 'child_process'; uses ES module default import incorrectly; const exec = require('exec'); tries to require a non-existent module; import { exec } from 'child_process'; is ES module named import but Node.js needs special config.
  3. Final Answer:

    const exec = require('child_process').exec; -> Option B
  4. Quick Check:

    CommonJS import for exec = A [OK]
Hint: Use require('child_process').exec for standard Node.js [OK]
Common Mistakes:
  • Using import without Node.js ES module setup
  • Requiring wrong module name
  • Confusing default and named imports
3. What will the following Node.js code output if the current directory contains a file named test.txt?
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(`Output: ${stdout}`);
});
medium
A. Output: test.txt
B. Error: ls command not found
C. Stderr: Permission denied
D. No output

Solution

  1. Step 1: Understand exec running 'ls'

    The command ls lists files in the current directory. If test.txt exists, it will appear in the output.
  2. Step 2: Analyze callback behavior

    No error or stderr means output is printed with file names, so console logs 'Output: test.txt\n'.
  3. Final Answer:

    Output: test.txt -> Option A
  4. Quick Check:

    exec runs ls, outputs files = A [OK]
Hint: exec callback logs stdout if no error or stderr [OK]
Common Mistakes:
  • Assuming error if command runs successfully
  • Ignoring stdout content
  • Confusing stderr with stdout
4. Identify the error in this Node.js code using exec:
const { exec } = require('child_process');
exec('node -v', (error, stdout, stderr) => {
  if (error) {
    console.log(error);
  }
  console.log(stdout);
});
medium
A. Callback function has wrong parameters
B. Incorrect command syntax for node version
C. Missing error return causes stdout to print even on error
D. exec is not imported correctly

Solution

  1. Step 1: Check error handling logic

    The code logs error but does not return or stop, so stdout logs even if error occurs.
  2. Step 2: Understand impact of missing return

    This can cause confusing output mixing error and stdout, which is not ideal.
  3. Final Answer:

    Missing error return causes stdout to print even on error -> Option C
  4. Quick Check:

    Missing error return causes stdout to print even on error = D [OK]
Hint: Return after error to avoid printing stdout [OK]
Common Mistakes:
  • Not returning after error check
  • Assuming exec import is wrong
  • Thinking command syntax is incorrect
5. You want to run a shell command that lists all files but only print those containing the word 'log'. Which exec usage correctly achieves this in Node.js?
hard
A. exec('ls > grep log', (err, stdout) => { if (!err) console.log(stdout); });
B. exec('ls && grep log', (err, stdout) => { if (!err) console.log(stdout); });
C. exec('ls | find log', (err, stdout) => { if (!err) console.log(stdout); });
D. exec('ls | grep log', (err, stdout) => { if (!err) console.log(stdout); });

Solution

  1. Step 1: Understand shell command chaining

    The pipe | sends output of ls to grep log to filter lines containing 'log'.
  2. Step 2: Evaluate each option's command

    ls | grep log correctly pipes output to grep for filtering; ls > grep log uses redirection to create a file; ls && grep log runs sequentially without piping; ls | find log pipes to filesystem search tool unsuitable for text filtering.
  3. Final Answer:

    exec('ls | grep log', (err, stdout) => { if (!err) console.log(stdout); }); -> Option D
  4. Quick Check:

    Pipe output to grep for filtering = C [OK]
Hint: Use pipe (|) to filter command output with grep [OK]
Common Mistakes:
  • Using && instead of | for piping output
  • Misusing redirection operators
  • Confusing grep with find command