Language: EN

cheatsheet-nodejs

Node.js Cheatsheet

Node.js is a JavaScript runtime environment primarily used for creating servers, handling HTTP requests, and building backend applications.

Installing Node.js

Installation on Windows

Download the Node.js installer from nodejs.org.

Installation on Linux

To install Node.js on Ubuntu:

sudo apt update
sudo apt install nodejs npm

Installation on macOS

Use Homebrew to install Node.js:

brew install node

Verify installation

node --version
npm --version

Basic Setup

Create a Node.js project

Start a new project and create a package.json file.

npm init

To skip questions and use default values, you can use:

npm init -y

Install dependencies

Install necessary dependencies for the project.

npm install package-name

Install development dependencies

Useful dependencies for the development environment, such as linters or testing tools.

npm install --save-dev package-name

Run a Node.js file

node file.js

Package Management with NPM

Install packages

Install external packages using npm:

npm install express

List installed dependencies

npm list

Uninstall packages

npm uninstall package-name

Modules and Exports

Node.js uses ECMAScript modules (import/export) to handle code reuse.

Import native modules

To import a native Node.js module, use the following syntax:

import { createServer } from 'node:http';

Import external modules

If you install an external module with npm, you can import it:

import express from 'express';

Export functions or variables

To export content from a module, use export:

export function myFunction() {
  // code
}

export const myConstant = 42;

Import the entire module

import * as fs from 'node:fs';

File Management

Node.js includes the node:fs (File System) module to work with files and directories.

Read a file synchronously

import { readFileSync } from 'node:fs';

const data = readFileSync('file.txt', 'utf-8');
console.log(data);

Read a file asynchronously

import { readFile } from 'node:fs/promises';

async function readFileAsync() {
  const data = await readFile('file.txt', 'utf-8');
  console.log(data);
}

readFileAsync();

Write to a file synchronously

import { writeFileSync } from 'node:fs';

writeFileSync('file.txt', 'New content');

Write to a file asynchronously

import { writeFile } from 'node:fs/promises';

await writeFile('file.txt', 'New content');

HTTP Server

The node:http module is essential for creating web servers in Node.js.

Basic HTTP server

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, world\n');
});

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

Handling different routes

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Home page');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Page not found');
  }
});

server.listen(3000);

Promises and async/await

Node.js supports the use of promises and async/await to handle asynchronous code in a more readable manner.

Promises

const promise = new Promise((resolve, reject) => {
  const success = true;
  if (success) {
    resolve('Operation successful');
  } else {
    reject('Error in operation');
  }
});

promise
  .then((message) => {
    console.log(message);
  })
  .catch((error) => {
    console.log(error);
  });

Async/Await

async function asyncExample() {
  try {
    const result = await promise;
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

asyncExample();

Events and Streams

Node.js uses an event and stream system to handle data.

Creating an event emitter

import { EventEmitter } from 'node:events';

const emitter = new EventEmitter();

emitter.on('event', () => {
  console.log('Event triggered');
});

emitter.emit('event');

Reading a file as a stream

import { createReadStream } from 'node:fs';

const stream = createReadStream('file.txt', 'utf-8');

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

stream.on('end', () => {
  console.log('Reading completed');
});

Writing to a file as a stream

import { createWriteStream } from 'node:fs';

const stream = createWriteStream('file.txt');

stream.write('Writing data to a file\n');
stream.end('Finalizing the file');

Error Management

Try/Catch

try {
  throw new Error('An error has occurred');
} catch (error) {
  console.error(error.message);
}

Handling errors in asynchronous code

async function asyncExampleWithErrors() {
  try {
    const result = await failedPromise();
  } catch (error) {
    console.log('Captured error:', error.message);
  }
}

asyncExampleWithErrors();

Debugging in Node.js

Node.js includes tools for debugging.

Start Node.js in debugging mode

node --inspect file.js

Then open chrome://inspect in Chrome to connect to the debugger.