Core Modules
| Module | Purpose |
|---|
fs | File system operations (sync/async) |
path | Path manipulation (join, resolve, extname) |
http | HTTP server/client |
url | URL parsing (parse, format) |
os | OS info (platform, cpus, freemem) |
events | EventEmitter pattern |
crypto | Hashing, encryption |
child_process | Spawn subprocesses (exec, spawn) |
stream | Readable/Writable streams |
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');
Async Patterns
| Pattern | Example |
|---|
| Callback | fs.readFile('f.txt', (err, data) => {}) |
| Promise | fs.promises.readFile('f.txt').then(...) |
| async/await | const data = await fs.promises.readFile('f.txt') |
| EventEmitter | emitter.on('event', fn) / emitter.emit('event') |
// EventEmitter
const ee = new EventEmitter();
ee.on('data', (d) => console.log(d));
ee.emit('data', 'hello');
File System Operations
| Operation | Sync | Async |
|---|
| Read file | fs.readFileSync(path) | fs.readFile(path, callback) |
| Write file | fs.writeFileSync(path, data) | fs.writeFile(path, data, callback) |
| Read dir | fs.readdirSync(path) | fs.readdir(path, callback) |
| Stats | fs.statSync(path) | fs.stat(path, callback) |
| Watch | β | fs.watch(path, (ev, name) => {}) |
// Streams
const rs = fs.createReadStream('in.txt');
const ws = fs.createWriteStream('out.txt');
rs.pipe(ws);
HTTP Server Basics
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello');
});
server.listen(3000);
| Method | Purpose |
|---|
req.url | Request path |
req.method | GET, POST, etc. |
res.writeHead(status, headers) | Set response headers |
res.end(body) | Send and close |
Process & Environment
| Item | Purpose |
|---|
process.env | Environment variables |
process.argv | CLI args [node, script, ...] |
process.exit(code) | Exit with code (0=ok) |
process.cwd() | Current working directory |
process.platform | 'darwin', 'win32', etc. |
const [,, arg1, arg2] = process.argv;
const port = process.env.PORT || 3000;
npm Commands
| Command | Purpose |
|---|
npm init | Create package.json |
npm init -y | Init with defaults |
npm install | Install deps |
npm install pkg | Add dependency |
npm install -D pkg | Add devDependency |
npm run <script> | Run script from package.json |
npm publish | Publish to registry |
npm link | Link local package globally |
npm outdated | Check outdated deps |
npm audit | Security audit |
package.json Fields
| Field | Purpose |
|---|
name | Package name |
version | Semver (e.g. 1.0.0) |
main | Entry point |
scripts | npm run scripts |
dependencies | Prod deps |
devDependencies | Dev deps |
type | "module" for ESM |
exports | Conditional exports |
Module System
| Style | Syntax |
|---|
| CommonJS | const x = require('x') / module.exports = x |
| ES Modules | import x from 'x' / export default x |
// CommonJS
module.exports = { foo, bar };
exports.foo = foo;
// ESM (package.json: "type": "module")
export default fn;
export { a, b };
Error Handling
// Callback: err first
fs.readFile('f.txt', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
// async/await: try/catch
try {
const data = await fs.promises.readFile('f.txt');
} catch (err) {
console.error(err);
}
Useful Globals
| Global | Purpose |
|---|
Buffer | Binary data |
__dirname | Dir of current module (CJS) |
__filename | Path of current module (CJS) |
setTimeout(fn, ms) | Run after delay |
setInterval(fn, ms) | Run repeatedly |
clearTimeout(id) | Cancel timeout |
console | log, error, warn, etc. |
global | Global object |
// Buffer
Buffer.from('hello');
Buffer.alloc(10);
// __dirname in ESM: use import.meta.url
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));