Process Control

Back

Loading concept...

Process Control in Node.js 🎮

The Story of Your Program’s Remote Control

Imagine you’re playing with a toy robot. This robot can:

  • Tell you where it’s standing right now
  • Walk to a different room when you ask
  • Turn itself off when it’s done playing
  • Wave a flag to show if it finished happy or sad
  • Tell you how tired or hungry it is

In Node.js, your program is like that robot. And process is the remote control that lets you check on it and tell it what to do!


🗺️ Where Am I? (process.cwd())

CWD = Current Working Directory

Think of it like asking: “Hey robot, which room are you in right now?”

const currentFolder = process.cwd();
console.log(currentFolder);
// Output: /home/user/my-project

Why Does This Matter?

When your program reads or writes files, it starts looking from this folder. It’s like your robot’s “home base.”

graph TD A["Your Program Starts"] --> B["process.cwd"] B --> C["/home/user/my-project"] C --> D["All file paths start here!"]

Real Example

const fs = require('fs');

// This looks for data.txt in the CWD
fs.readFileSync('data.txt');

// Same as writing the full path:
fs.readFileSync(process.cwd() + '/data.txt');

🚶 Move to a Different Room (process.chdir())

CHDIR = Change Directory

Your robot can walk to a different room! Now all its work happens there.

console.log(process.cwd());
// /home/user/my-project

process.chdir('/home/user/other-folder');

console.log(process.cwd());
// /home/user/other-folder

⚠️ Watch Out!

If you try to go to a room that doesn’t exist, your robot trips and falls (error)!

try {
  process.chdir('/fake/path');
} catch (err) {
  console.log('Oops! That folder does not exist.');
}

When Would You Use This?

  • Running scripts that need to work in a specific folder
  • Processing files in different locations
  • Build tools that compile code in various directories

👋 Time to Say Goodbye (process.exit())

When your robot is done playing, it turns itself off. In Node.js, process.exit() stops your program immediately.

console.log('Starting...');
console.log('Working...');
process.exit();
console.log('This never runs!');

The Magic Number: Exit Codes

When your robot turns off, it waves a flag with a number:

  • 0 = “I finished perfectly! Everything went great!” 🎉
  • 1 = “Something went wrong…” 😢
  • Any other number = Different types of problems
// Happy exit (success)
process.exit(0);

// Sad exit (something failed)
process.exit(1);

🚩 Exit Codes Explained

Exit codes are like report cards for your program. Other programs can check this number to know what happened.

Code Meaning
0 Success! All good!
1 General error
2 Misuse of command
126 Permission problem
127 Command not found
128+ Special signals

Real-World Example

const fs = require('fs');

try {
  const data = fs.readFileSync('important.txt');
  console.log('File read successfully!');
  process.exit(0); // Success!
} catch (err) {
  console.error('Could not read file!');
  process.exit(1); // Failure!
}

Why Exit Codes Matter

When you chain programs together (like in scripts), each program checks if the previous one succeeded:

node step1.js && node step2.js && node step3.js

If step1.js exits with code 1, step2.js never runs!


📊 How’s My Robot Feeling? (Resource Monitoring)

Your robot can tell you:

  • How much brain power (memory) it’s using
  • How long it’s been awake (uptime)
  • How much work it’s done (CPU time)

Memory Usage

const memory = process.memoryUsage();

console.log(memory);
// {
//   heapTotal: 4000000,  (Total brain space)
//   heapUsed: 2500000,   (Brain space in use)
//   external: 1000000,   (Outside helpers)
//   rss: 25000000        (Total memory footprint)
// }

Make It Human-Readable

function formatBytes(bytes) {
  return (bytes / 1024 / 1024).toFixed(2) + ' MB';
}

const mem = process.memoryUsage();
console.log('Using:', formatBytes(mem.heapUsed));
// Output: Using: 2.38 MB

Uptime: How Long Have I Been Running?

console.log(process.uptime());
// 45.123 (seconds since program started)

CPU Usage

const cpu = process.cpuUsage();

console.log(cpu);
// {
//   user: 500000,   (Work time in microseconds)
//   system: 100000  (System call time)
// }

🎯 Putting It All Together

Here’s a complete example that uses everything we learned:

const fs = require('fs');

console.log('Starting in:', process.cwd());
console.log('Been running for:', process.uptime(), 'seconds');

// Check memory before work
const memBefore = process.memoryUsage().heapUsed;

try {
  // Change to data folder
  process.chdir('./data');
  console.log('Moved to:', process.cwd());

  // Do some work...
  const files = fs.readdirSync('.');
  console.log('Found', files.length, 'files');

  // Check memory after work
  const memAfter = process.memoryUsage().heapUsed;
  console.log('Memory used:', memAfter - memBefore, 'bytes');

  // Success!
  process.exit(0);

} catch (err) {
  console.error('Error:', err.message);
  process.exit(1);
}

🧠 Quick Summary

graph TD P["process"] --> A["cwd - Where am I?"] P --> B["chdir - Move somewhere"] P --> C["exit - Turn off"] P --> D["Exit Codes - Report card"] P --> E["Resources - How am I doing?"] E --> E1["memoryUsage"] E --> E2["uptime"] E --> E3["cpuUsage"]

Remember:

Command What It Does Like…
process.cwd() Gets current folder “Where am I?”
process.chdir(path) Changes folder “Walk to room”
process.exit(code) Stops program “Turn off robot”
Exit code 0 Success Happy flag 🎉
Exit code 1+ Error Sad flag 😢
process.memoryUsage() RAM info “How’s my brain?”
process.uptime() Seconds running “How long awake?”
process.cpuUsage() CPU time “How hard working?”

🚀 You Did It!

Now you know how to:

  • ✅ Find where your program is running
  • ✅ Move to different folders
  • ✅ Stop your program with proper exit codes
  • ✅ Monitor your program’s health

Your program’s remote control is now in your hands! Go build something amazing! 🎮

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.