Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Node.js Cheat Sheet

CLI and npm

// run, watch, install, scripts
node app.js
node --watch app.js
npm init -y
npm i express mongoose dotenv
npm i -D nodemon
npm run dev
npx some-tool

Modules and paths

const fs = require("node:fs"); module.exports = { fn };
import express from "express"; export default app;
path.join(__dirname, "public"); path.extname(file); path.basename(file);
process.env.PORT; process.argv.slice(2); process.exit(1);

Files

fs.readFileSync(file, "utf8"); fs.writeFileSync(file, data);
await fsp.readFile(file, "utf8"); await fsp.writeFile(file, data);
await fsp.mkdir(dir, { recursive: true }); fs.existsSync(file);

Express

const app = express(); app.use(express.json()); app.use(cors());
app.get("/api/items", (req, res) => res.json(items));
app.post("/api/items", (req, res) => res.status(201).json(req.body));
req.params.id; req.query.page; req.body.name; req.headers.authorization;
res.status(404).json({ message: "Not found" });
const router = express.Router(); app.use("/api/users", router);
app.listen(5000, () => console.log("running"));

Async

await Promise.all([a(), b()]); await Promise.allSettled(list);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
emitter.on("event", fn); emitter.emit("event", data);

Mongoose

await mongoose.connect(process.env.MONGO_URI);
const User = mongoose.model("User", new mongoose.Schema({ name: String }));
await User.create(doc); await User.find(filter).sort({ createdAt: -1 }).limit(10);
await User.findById(id); await User.updateOne(filter, { $set: data }); await User.deleteOne(filter);

Full Node.js documentation