Previous chapter: Chapter 23: JavaScript Performance and Optimization
1. What is Node.js?
Node.js uses the same V8 JavaScript engine found in Chrome to run JS files directly from the command line.
Key Differences from Browser JS
| Feature | Browser JavaScript | Node.js |
|---|
| Global Object | window, document | global, process |
| I/O Access | Restricted (cannot access files) | Full access to the File System and network |
| Modules | ES Modules (import/export) or script tags | Supports ES Modules and CommonJS (require/module.exports) |
2. The fs Module (File System)
The built-in fs (File System) module allows Node.js to interact with the server's file system, reading and writing files.
// Import the File System moduleconst fs = require('fs'); // CommonJS module import syntax
const filePath = 'greetings.txt';
const content = 'Hello from Node.js!';
// Asynchronously write to a file (non-blocking)
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('File successfully written!');
// Asynchronously read the file back
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) throw err;
console.log('File content:', data);
});
}
});
3. Basic HTTP Server
Node.js is most often used to create web servers that listen for requests (like a browser fetching a webpage or an API request). The built-in http module handles this.
const http = require('http');
const server = http.createServer((req, res) => {
// req: Request object (client data, URL, headers)
// res: Response object (what we send back to the client)
// Set the HTTP header for a successful response (200 OK)
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body
res.end('My first Node.js server is running!');
});
const PORT = 3000;
server.listen(PORT, () => {
// This runs once the server is successfully listening
console.log(`Server listening on http://localhost:${PORT}`);
});
4. Package Creation (module.exports)
When creating a Node.js module (a library you want to share), you use the CommonJS syntax (require/module.exports) to expose functions and variables.
// calculator.js (Node.js module)const PI = 3.14159;
function area(radius) {
return PI * radius * radius;
}
// Export the functions/variables you want to exposemodule.exports = {
PI,
calculateArea: area
};
This is a foundational step for building backends using frameworks like Express.js.