💻

Node.js Crash Course

Aug 10, 2024

Node.js Crash Course 💻

Introduction

  • No frameworks used (e.g., Express, Fastify, Adonis)
  • Focus is on low-level understanding
  • Suitable for all skill levels
  • We'll set up a server, explore HTTP module, and other core Node.js modules

What is Node.js?

  • JavaScript runtime, not a framework, library, or language
  • Built with C++ and uses the V8 JavaScript engine (used in Google Chrome)
  • Used for server-side, networking applications, APIs, microservices
  • JavaScript becomes a full-stack language with Node.js
  • Good alternatives: Deno, Bun.js (though Node.js more mature/supported)

Installing Node.js

  • Go to nodejs.org, download LTS (recommended) or latest
  • Verify installation using node --version and npm --version
  • Node.js comes with npm (Node Package Manager)
  • REPL available by typing node

Setting Up a Node.js Project

  • Create project directory: mkdir nodejs-crash-2024
  • Initialize project: npm init
  • Create entry point file (e.g., index.js)
  • Run file: node index.js
  • CommonJS modules: module.exports and require
  • ES Modules: export keyword and import syntax

Core Node.js Modules

HTTP Module

  • Setting up basic HTTP server: http.createServer()
  • Methods: req.method, res.write, res.end, res.setHeader
  • Managing status codes: res.statusCode
  • Example HTTP server: const http = require('http'); const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.write('<h1>Hello, World!</h1>'); res.end(); });

Middleware

  • Functions handling requests/responses
  • Example Logger Middleware: const logger = (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); };

File System (FS) Module

  • Reading files: fs.readFile(), fs.readFileSync(), fs.promises.readFile
  • Writing files: fs.writeFile(), fs.promises.writeFile
  • Appending files: fs.appendFile(), fs.promises.appendFile
  • Example for reading a file: const fs = require('fs'); fs.readFile('test.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });

Path Module

  • Utility for file and directory paths
  • Methods: path.basename(), path.dirname(), path.extname(), path.parse(), path.join()
  • Example: const path = require('path'); console.log(path.basename('/foo/bar/baz/asdf/test.txt')); // returns 'test.txt'

OS Module

  • Provides information about the operating system
  • Methods: os.userInfo(), os.totalmem(), os.freemem(), os.cpus()
  • Example: const os = require('os'); console.log(os.userInfo()); console.log(os.totalmem()); console.log(os.freemem()); console.log(os.cpus());

URL Module

  • Parse URLs and query strings
  • Example: const { URL } = require('url'); const myURL = new URL('https://example.org/foo'); console.log(myURL.href); // returns 'https://example.org/foo'

Crypto Module

  • Provides cryptographic functionality
  • Example (Hashing): const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update('password1234'); console.log(hash.digest('hex'));

Event Emitter

  • Create and handle custom events
  • Example: const EventEmitter = require('events'); const myEmitter = new EventEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event');

Conclusion

  • Foundation of Node.js covered
  • Recommended next steps: Express.js, deeper dive into APIs & middleware
  • Resources: Node.js documentation, Express.js crash course, Node.js API masterclass on TraverseMedia.com and Udemy