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.
| Name | Signature / Syntax | Description |
|---|---|---|
| require | const fs = require('fs') | Import CommonJS module (legacy Node) |
| import | import fs from 'fs/promises' | Import ES module (add type:module to package.json) |
| fs.readFile | fs.readFile(path, 'utf8', callback) | Read file asynchronously (callback) |
| fs.readFileSync | fs.readFileSync(path, 'utf8') → string | Read file synchronously |
| fs.writeFile | fs.writeFile(path, data, callback) | Write file asynchronously |
| fs.promises.readFile | await fs.promises.readFile(path, 'utf8') | Read file with async/await |
| fs.promises.writeFile | await fs.promises.writeFile(path, data) | Write file with async/await |
| fs.promises.readdir | await fs.promises.readdir(dir) | List directory contents |
| fs.promises.mkdir | await fs.promises.mkdir(dir, {recursive:true}) | Create directory |
| fs.promises.stat | await fs.promises.stat(path) | Get file metadata |
| path.join | path.join(dir, 'sub', 'file.txt') | Join path components (OS-aware) |
| path.resolve | path.resolve('./relative') | Resolve to absolute path |
| path.dirname | path.dirname('/foo/bar.txt') → '/foo' | Directory part of path |
| path.basename | path.basename('/foo/bar.txt') → 'bar.txt' | Filename part of path |
| path.extname | path.extname('file.js') → '.js' | Extension part of path |
| http.createServer | http.createServer((req,res) => {}) | Create HTTP server |
| req.url / req.method | req.url → string / req.method → string | Request URL and HTTP method |
| res.writeHead | res.writeHead(200, {'Content-Type':'text/html'}) | Set status and headers |
| res.end | res.end(body) | Send response and close connection |
| process.env | process.env.PORT || 3000 | Access environment variables |
| process.argv | process.argv[2] | Command-line arguments |
| process.cwd | process.cwd() → string | Current working directory |
| process.exit | process.exit(0) | Exit Node process |
| console.log/error | console.log() / console.error() | Log to stdout / stderr |
| __dirname | __dirname | Directory of current module (CommonJS) |
| __filename | __filename | Path of current module (CommonJS) |
| Buffer | Buffer.from('hello') / Buffer.alloc(n) | Work with binary data |
| EventEmitter | const ee = new EventEmitter() | Publish-subscribe pattern |
| stream.Readable | new Readable({ read() {} }) | Create readable stream |
| stream.pipeline | pipeline(readable, writable, cb) | Safely pipe streams |
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}'