Node.js Basics
Run JavaScript on the server/CLI with Node.js. Access file system, processes, and network APIs.
Modules
Use ESM (recommended) with "type": "module" or .mjs; CJS remains common in legacy code.
// ESM
import { readFile } from 'node:fs/promises'
const text = await readFile('file.txt', 'utf8')
// CJS
const fs = require('fs')
const text2 = fs.readFileSync('file.txt', 'utf8')
fs and path
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
await mkdir('out', { recursive: true })
await writeFile(join('out', 'data.txt'), 'hello')
process
Environment, args, exit codes.
process.env.NODE_ENV
process.argv.slice(2)
process.exit(0)
CLI scripting
Use shebang and make executable.
#!/usr/bin/env node
console.log('Hello from Node')
HTTP (built-in)
import http from 'node:http'
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('ok')
}).listen(3000)
Prefer frameworks like Express/Fastify for apps.
Summary
- Prefer ESM; use fs/path/process for I/O and env
- Build CLIs with shebang and
process.argv; use built‑in HTTP or frameworks