Node.js uses an event-driven, non-blocking I/O model for asynchronous operations. Callbacks are functions passed as arguments to handle results after an async operation completes.
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
Use the http
module:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('GET request');
} else if (req.method === 'POST') {
res.end('POST request');
}
});
server.listen(3000);
Use fs
module:
const data = fs.readFileSync('file.txt', 'utf8');
fs.readFile('file.txt', 'utf8', (err, data) => { console.log(data); });
express
)Node is lightweight due to its non-blocking, event-driven architecture and V8 engine, which minimizes overhead and handles many concurrent connections efficiently.
Express features include middleware support, routing, HTTP utilities, and template engines for building RESTful APIs and web apps.