Node.js Quick Reference
Concise guide to Node.js with practical examples
Node.js Quick Reference
Node.js is a JavaScript runtime for building fast, scalable server-side and networking applications.
Installation
node --version
npm --version
npm init -yBasic HTTP Server
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});Using npm Packages
npm install express// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Express server running on http://localhost:3000');
});Reading and Writing Files
const fs = require('fs');
// Write to a file
fs.writeFileSync('hello.txt', 'Hello, file!');
// Read from a file
const content = fs.readFileSync('hello.txt', 'utf8');
console.log(content);Environment Variables
export MY_SECRET=12345 # On Windows use: set MY_SECRET=12345console.log(process.env.MY_SECRET);Asynchronous Programming
// Callback
fs.readFile('hello.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Promise
const fsPromises = require('fs').promises;
fsPromises.readFile('hello.txt', 'utf8')
.then(data => console.log(data));
// Async/Await
async function readFile() {
const data = await fsPromises.readFile('hello.txt', 'utf8');
console.log(data);
}
readFile();Best Practices
- Use
constandletinstead ofvar. - Handle errors in callbacks and promises.
- Use environment variables for secrets.
- Organize code into modules.
- Use async/await for asynchronous code.
