This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Node.js Core API Cheatsheet

A quick reference guide for Node.js core runtime APIs: global objects, child process execution and spawning, inspect formatting, and process streams.

· Published

Node.js is a JavaScript runtime built on Chrome's V8 engine that runs asynchronous event-driven code on servers.

Global Variables

Common module-level globals in CommonJS:

__filename; // Absolute file path of current module
__dirname;  // Absolute directory path of current module

Child Processes

child_process.exec()

Buffers process output and passes stdout/stderr to a callback (ideal for small scripts):

const { exec } = require('child_process');

exec('ls -la | grep .js', (error, stdout, stderr) => {
  if (error) {
    console.error(`Execution error: ${error.message}`);
    return;
  }
  console.log(`Output: ${stdout}`);
});

child_process.spawn()

Streams process data without buffering (ideal for long-running processes and large output):

const { spawn } = require('child_process');

// Inherit stdin/stdout/stderr directly in terminal
const child = spawn('npm', ['test'], { stdio: 'inherit' });

child.on('error', (err) => {
  if (err.code === 'ENOENT') console.error('Executable not found');
  if (err.code === 'EACCES') console.error('Permission denied');
});

child.on('exit', (code, signal) => {
  console.log(`Process exited with code ${code}`);
});

Formatting & Inspection

const util = require('util');

// Inspect complex objects deeply with syntax highlighting
const output = util.inspect(complexObject, {
  showHidden: false,
  depth: null, // Unlimited depth
  colors: true
});

process.stdout.write(output + '\n');

References

Related topics