Youssef Samir

Get in touch

Node.js

A practical guide to frequently used Node.js commands, modules, and patterns for efficient server-side JavaScript development.

File System (fs) Module Functions

Writing Files

  • fs.writeFile(path, data, options, callback)
    Asynchronously writes data to a file, replacing the file if it exists.
fs.writeFile('/path/to/file', 'Hello World!', err => {   if (err) throw err;   console.log('The file has been saved!'); });

Creating Directories

  • fs.mkdir(path, options, callback)
    Creates a new directory asynchronously.

fs.mkdir('/path/to/directory', { recursive: true }, err => { if (err) throw err; console.log('Directory created successfully'); });`

Checking Existence

  • fs.existsSync(path)
    Synchronously checks if a path exists.

if (fs.existsSync('/path/to/file')) { console.log('File exists'); } else { console.log('File does not exist'); }

Removing Directories

  • fs.rmdir(path, options, callback)
    Removes a directory asynchronously.
fs.rmdir('/path/to/directory', err => {   if (err) throw err;   console.log('Directory removed successfully'); });

Deleting Files

  • fs.unlink(path, callback)
    Deletes a file asynchronously.
fs.unlink('/path/to/file', err => {   if (err) throw err;   console.log('File deleted successfully'); });

Reading and Writing Streams

  • fs.createReadStream(path, options)
    Creates a readable stream.
const readStream = fs.createReadStream('/path/to/file');
  • fs.createWriteStream(path, options)
    Creates a writable stream.
const writeStream = fs.createWriteStream('/path/to/file');
  • readStream.on(event, listener)
    Registers event listeners on the readable stream.
readStream.on('data', chunk => {   console.log(chunk); });
  • readStream.pipe(destination, options)
    Pipes the readable stream to a destination.
readStream.pipe(writeStream);

NPM Packages

Nodemon

  • nodemon
    Automatically restarts your application when file changes in the directory are detected. npm install --save-dev nodemon

Add to package.json scripts: "scripts": { "start": "nodemon index.js" }

Express

  • express
    Fast, unopinionated, minimalist web framework for Node.js.

npm install express

Example usage:

const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello World')); app.listen(3000, () => console.log('Server running on port 3000'));

EJS

  • ejs
    A high-performance template engine for generating HTML markup with plain JavaScript.

npm install ejs

Example usage:

app.set('view engine', 'ejs'); app.get('/', (req, res) => res.render('index', { title: 'Home Page' }));

Morgan

  • morgan
    HTTP request logger middleware for Node.js.

npm install morgan

Example usage:

const morgan = require('morgan'); app.use(morgan('combined'));