Let's think about it this way for a moment
This lesson isn't about learning anything new — it's a practice set for confirming, through hands-on code, the concepts you learned in the Modules, fs Module, path Module, and http Module lessons. You'll practice three things: creating files, joining paths so they work across platforms, and running a simple HTTP server. Open your editor and run each task with the node command, and how the fs, path, and http modules work will become much clearer. Even at beginner level, be careful to include error handling.
Exercises
Task 1: Use fs.writeFile to create a file called todo.txt with some string content, then read it back with fs.readFile and console.log it. Task 2: Use path.join() to combine two folders (data, logs) into a single path, then use path.basename() to extract just the file name. Task 3: Write a server with http.createServer() that runs on port 4000 — if the request URL is '/time', return the current time as JSON; for any other URL, return 404. Task 4 (optional): Rewrite the file write/read logic from Task 1 as a function, and log any error with console.error.
Code Example
const fs = require('fs');
const path = require('path');
const http = require('http');
// Task 1: write + read a file
fs.writeFile('todo.txt', 'Learn Node.js modules\n', 'utf8', (err) => {
if (err) return console.error('Write failed:', err.message);
fs.readFile('todo.txt', 'utf8', (err2, data) => {
if (err2) return console.error('Read failed:', err2.message);
console.log('File content:', data);
});
});
// Task 2: path practice
const fullPath = path.join('data', 'logs', 'app.log');
console.log('Joined path:', fullPath);
console.log('Base name:', path.basename(fullPath));
// Task 3: mini http server
const server = http.createServer((req, res) => {
if (req.url === '/time') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ now: new Date().toISOString() }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(4000, () => console.log('Server running on port 4000'));A todo.txt file gets created and its content is logged to the terminal, and opening http://localhost:4000/time in the browser returns JSON containing the current time.5-Minute Try
In 5 minutes, modify Task 3 to add a new '/hello' route — when a request comes in, make it return the JSON '{ "message": "Hello Node.js" }'.
A Quick Warning
Always use path.join() instead of manually concatenating strings ('data' + '/' + 'logs') — Windows and Linux use different slash characters, which can cause bugs.