logo
eng-flag

Node.js Cheatsheet

Table of Contents

  1. Setup and Installation
  2. Modules
  3. File System
  4. Streams
  5. Events
  6. HTTP Server
  7. Buffer
  8. Path
  9. OS
  10. Child Process

Setup and Installation

Installing Node.js

Visit https://nodejs.org and download the installer for your operating system.

Checking Node.js and npm versions

node --version
npm --version

Modules

Creating and Exporting a Module

// greet.js
module.exports = {
  sayHello: function(name) {
    return `Hello, ${name}!`;
  }
};

Importing a Module

const greet = require('./greet');
console.log(greet.sayHello('John')); // Output: Hello, John!

Core Modules

const fs = require('fs');
const http = require('http');
const path = require('path');

File System

Reading a File

const fs = require('fs');

// Asynchronous
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Synchronous
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);

Writing to a File

const fs = require('fs');

// Asynchronous
fs.writeFile('file.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File saved!');
});

// Synchronous
fs.writeFileSync('file.txt', 'Hello, World!');

Appending to a File

const fs = require('fs');

fs.appendFile('file.txt', 'More content
', (err) => {
  if (err) throw err;
  console.log('Content appended!');
});

Streams

Reading from a Stream

const fs = require('fs');

const readStream = fs.createReadStream('file.txt', 'utf8');

readStream.on('data', (chunk) => {
  console.log(chunk);
});

readStream.on('end', () => {
  console.log('Finished reading');
});

Writing to a Stream

const fs = require('fs');

const writeStream = fs.createWriteStream('file.txt');

writeStream.write('Hello, ');
writeStream.write('World!');
writeStream.end();

Piping Streams

const fs = require('fs');

const readStream = fs.createReadStream('input.txt');
const writeStream = fs.createWriteStream('output.txt');

readStream.pipe(writeStream);

Events

Creating an Event Emitter

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

Handling Events

myEmitter.on('event', () => {
  console.log('Event occurred!');
});

myEmitter.emit('event');

HTTP Server

Creating a Basic HTTP Server

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000/');
});

Buffer

Creating a Buffer

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.from('Hello, World!');

Writing to a Buffer

buf1.write('Hello');

Reading from a Buffer

console.log(buf1.toString());
console.log(buf2.toString('utf8', 0, 5)); // Output: Hello

Path

Working with Paths

const path = require('path');

console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')); 
// Output: /foo/bar/baz/asdf

console.log(path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'));
// Output: /tmp/subfile

console.log(path.extname('index.html')); 
// Output: .html

OS

Getting OS Information

const os = require('os');

console.log(os.platform());
console.log(os.arch());
console.log(os.cpus());
console.log(os.totalmem());
console.log(os.freemem());

Child Process

Spawning a Child Process

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

const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Executing a Command

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

exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stderr}`);
});

2024 © All rights reserved - buraxta.com