Node.js 20 Guide
Node.jsJavaScript Runtime
Learn Node.js fundamentals, event loop, streams, async patterns, and building scalable server applications.
Contents
Node.js Basics
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server.
javascript
// Creating a Simple Server
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
// File System Operations
const fs = require('fs');
// Read file asynchronously
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
// Read file synchronously (blocking)
const data = fs.readFileSync('file.txt', 'utf8');
// Write file
fs.writeFile('output.txt', 'Hello Node.js!', (err) => {
if (err) console.error(err);
else console.log('File written successfully');
});
// Process Object
console.log(process.argv); // Command line arguments
console.log(process.env); // Environment variables
process.exit(0); // Exit process