Node.js Quick Reference

Concise guide to Node.js with practical examples

Node.js Quick Reference

Node.js is a JavaScript runtime for building fast, scalable server-side and networking applications.

Installation

node --version
npm --version
npm init -y

Basic HTTP Server

// server.js
const http = require('http');

const server = http.createServer((req, res) => {
	res.writeHead(200, { 'Content-Type': 'text/plain' });
	res.end('Hello, Node.js!');
});

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

Using npm Packages

npm install express
// app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
	res.send('Hello from Express!');
});

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

Reading and Writing Files

const fs = require('fs');

// Write to a file
fs.writeFileSync('hello.txt', 'Hello, file!');

// Read from a file
const content = fs.readFileSync('hello.txt', 'utf8');
console.log(content);

Environment Variables

export MY_SECRET=12345 # On Windows use: set MY_SECRET=12345
console.log(process.env.MY_SECRET);

Asynchronous Programming

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

// Promise
const fsPromises = require('fs').promises;
fsPromises.readFile('hello.txt', 'utf8')
	.then(data => console.log(data));

// Async/Await
async function readFile() {
	const data = await fsPromises.readFile('hello.txt', 'utf8');
	console.log(data);
}
readFile();

Best Practices

  1. Use const and let instead of var.
  2. Handle errors in callbacks and promises.
  3. Use environment variables for secrets.
  4. Organize code into modules.
  5. Use async/await for asynchronous code.

Resources