0
0
Node.jsframework~15 mins

exec for running shell commands in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using exec to Run Shell Commands in Node.js
📖 Scenario: You are building a simple Node.js script that runs a shell command to list files in a folder. This is useful when you want your program to interact with the system shell to get information or run tools.
🎯 Goal: Create a Node.js script that uses exec from the child_process module to run the ls -l command and handle its output.
📋 What You'll Learn
Import the exec function from the child_process module
Create a variable command with the exact string ls -l
Use exec to run the command variable
Handle the callback to print the command output or error
💡 Why This Matters
🌍 Real World
Running shell commands from Node.js scripts helps automate system tasks, gather system info, or run external tools.
💼 Career
Many backend developers use exec to integrate system commands or scripts into their Node.js applications.
Progress0 / 4 steps
1
Import exec from child_process
Write a line to import exec from the child_process module using destructuring assignment.
Node.js
Need a hint?

Use const { exec } = require('child_process'); to import exec.

2
Create the command variable
Create a variable called command and set it to the string 'ls -l'.
Node.js
Need a hint?

Use const command = 'ls -l'; to store the shell command.

3
Run the command with exec
Use exec to run the command variable. Provide a callback with parameters error, stdout, and stderr.
Node.js
Need a hint?

Call exec(command, (error, stdout, stderr) => { ... }) to run the command.

4
Handle output and errors
Inside the exec callback, add code to check if error exists. If yes, return early. Otherwise, log stdout to the console.
Node.js
Need a hint?

Use if (error) { return; } to stop on error, then console.log(stdout); to show output.