NoNode.js · Lesson 7 of 7
Node.js Cheatsheet
Runtime APIs, modules, files, and servers on one page.
JavaScript
// ── Modules (ESM — "type": "module") ────
import fs from 'node:fs/promises'
import path from 'node:path'
import { readFile } from 'node:fs/promises'
export function helper() {}
export default main
// ── Files ───────────────────────────────
const text = await fs.readFile('data.txt', 'utf8')
await fs.writeFile('out.txt', text)
await fs.appendFile('log.txt', line)
await fs.mkdir('dir', { recursive: true })
const files = await fs.readdir('.')
const info = await fs.stat('file') // .isDirectory(), .size
// ── Paths & env ─────────────────────────
path.join(__dirname, 'data', 'f.txt')
path.resolve('..'); path.extname('a.md') // '.md'
process.env.PORT ?? 3000
process.argv.slice(2) // CLI args
process.exit(1)
import.meta.url // this file's URLJavaScript
// ── HTTP server (no framework) ──────────
import { createServer } from 'node:http'
createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ ok: true }))
}).listen(3000)
// ── Express (the standard framework) ────
import express from 'express'
const app = express()
app.use(express.json())
app.get('/users/:id', (req, res) => res.json({ id: req.params.id }))
app.post('/users', (req, res) => res.status(201).json(req.body))
app.listen(3000)
// ── Common tasks ────────────────────────
const res = await fetch(url) // built-in now
crypto.randomUUID()
setTimeout / setInterval / queueMicrotask
// child processes:
import { execSync } from 'node:child_process'
const out = execSync('git status', { encoding: 'utf8' })
// ── npm essentials ──────────────────────
// npm init -y | npm i pkg | npm i -D pkg | npx tool
// package.json scripts: "dev": "node --watch app.js"
// npm run dev