Chapters: JavaScript HTML & CSS JSON XML YAML Go Java ← Full TOC

← JavaScript Index

🟢 Node.js — Node.js — fs, http, path, process, npm modules

Node.js runs JavaScript on the server using Chrome's V8 engine. It provides built-in modules for file system, HTTP, networking, and process management. Non-blocking I/O makes it ideal for API servers and real-time applications.

📋 Methods & APIs

NameSignature / SyntaxDescription
requireconst fs = require('fs')Import CommonJS module (legacy Node)
importimport fs from 'fs/promises'Import ES module (add type:module to package.json)
fs.readFilefs.readFile(path, 'utf8', callback)Read file asynchronously (callback)
fs.readFileSyncfs.readFileSync(path, 'utf8') → stringRead file synchronously
fs.writeFilefs.writeFile(path, data, callback)Write file asynchronously
fs.promises.readFileawait fs.promises.readFile(path, 'utf8')Read file with async/await
fs.promises.writeFileawait fs.promises.writeFile(path, data)Write file with async/await
fs.promises.readdirawait fs.promises.readdir(dir)List directory contents
fs.promises.mkdirawait fs.promises.mkdir(dir, {recursive:true})Create directory
fs.promises.statawait fs.promises.stat(path)Get file metadata
path.joinpath.join(dir, 'sub', 'file.txt')Join path components (OS-aware)
path.resolvepath.resolve('./relative')Resolve to absolute path
path.dirnamepath.dirname('/foo/bar.txt') → '/foo'Directory part of path
path.basenamepath.basename('/foo/bar.txt') → 'bar.txt'Filename part of path
path.extnamepath.extname('file.js') → '.js'Extension part of path
http.createServerhttp.createServer((req,res) => {})Create HTTP server
req.url / req.methodreq.url → string / req.method → stringRequest URL and HTTP method
res.writeHeadres.writeHead(200, {'Content-Type':'text/html'})Set status and headers
res.endres.end(body)Send response and close connection
process.envprocess.env.PORT || 3000Access environment variables
process.argvprocess.argv[2]Command-line arguments
process.cwdprocess.cwd() → stringCurrent working directory
process.exitprocess.exit(0)Exit Node process
console.log/errorconsole.log() / console.error()Log to stdout / stderr
__dirname__dirnameDirectory of current module (CommonJS)
__filename__filenamePath of current module (CommonJS)
BufferBuffer.from('hello') / Buffer.alloc(n)Work with binary data
EventEmitterconst ee = new EventEmitter()Publish-subscribe pattern
stream.Readablenew Readable({ read() {} })Create readable stream
stream.pipelinepipeline(readable, writable, cb)Safely pipe streams

💡 Example

Run with node script.js or save as HTML and open in browser.

// Node.js HTTP Server + File System
// Save as server.js and run: node server.js
const http  = require('http');
const fs    = require('fs').promises;
const path  = require('path');
const url   = require('url');

const PORT = process.env.PORT || 8080;
const DATA_FILE = path.join(__dirname, 'data.json');

// Initialize data file
async function initData() {
  try { await fs.access(DATA_FILE); }
  catch { await fs.writeFile(DATA_FILE, JSON.stringify({ students: [] })); }
}

// Simple router
const routes = {
  'GET /': async (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`
      <h1>MyWebUniversity API</h1>
      <ul>
        <li>GET  /students</li>
        <li>POST /students  (JSON body)</li>
        <li>GET  /health</li>
      </ul>`);
  },
  'GET /health': async (req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'ok', uptime: process.uptime().toFixed(1) }));
  },
  'GET /students': async (req, res) => {
    const raw  = await fs.readFile(DATA_FILE, 'utf8');
    const data = JSON.parse(raw);
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data.students));
  },
  'POST /students': async (req, res) => {
    let body = '';
    for await (const chunk of req) body += chunk;
    const student = JSON.parse(body);
    const raw  = await fs.readFile(DATA_FILE, 'utf8');
    const data = JSON.parse(raw);
    data.students.push({ id: Date.now(), ...student });
    await fs.writeFile(DATA_FILE, JSON.stringify(data, null, 2));
    res.writeHead(201, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ ok: true, count: data.students.length }));
  },
};

const server = http.createServer(async (req, res) => {
  const { pathname } = url.parse(req.url);
  const key = `\${req.method} \${pathname}`;
  const handler = routes[key];
  if (handler) {
    try { await handler(req, res); }
    catch (e) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: e.message }));
    }
  } else {
    res.writeHead(404); res.end(JSON.stringify({ error: 'Not found' }));
  }
});

initData().then(() => {
  server.listen(PORT, () => console.log(`Server running on http://localhost:\${PORT}`));
});
// node server.js
// curl http://localhost:8080/health
// curl -X POST http://localhost:8080/students -H 'Content-Type:application/json' -d '{"name":"Alice","score":95}'

← DOM & Browser  |  🏠 Index