⚡ Lesson 27 of 30
Node.js Basics
Run JavaScript on the server with Node.js — file system, HTTP server, and the event loop.
Your First Node.js Script
In VS 2026, create server.js and run it with F5 or node server.js:
console.log("Node.js version:", process.version);
console.log("Platform:", process.platform);
console.log("Working dir:", process.cwd());
// Read command-line arguments
const args = process.argv.slice(2);
console.log("Arguments:", args);
File System (fs/promises)
import { readFile, writeFile, readdir } from "fs/promises";
async function main() {
// Write a file
await writeFile("hello.txt", "Hello from Node.js!\n");
// Read it back
const content = await readFile("hello.txt", "utf8");
console.log(content);
// List directory
const files = await readdir(".");
console.log(files);
}
main();
HTTP Server
Build a basic web server without any frameworks:
import { createServer } from "http";
const server = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`${req.method} ${req.url} — Hello from Node.js!\n`);
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
Environment Variables
Read config from .env files using Node.js 22+ built-in dotenv support:
// .env file:
// PORT=3000
// API_KEY=secret123
import { loadEnvFile } from "process";
loadEnvFile(); // loads .env
const PORT = process.env.PORT ?? 3000;
const KEY = process.env.API_KEY;
console.log(`Starting on port ${PORT}`);
Path & OS Modules
import path from "path";
import os from "os";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
console.log(path.join(__dirname, "data", "file.json"));
console.log(path.extname("app.test.js")); // ".js"
console.log(os.homedir());
console.log(os.cpus().length, "CPUs");