Student Activity
Student Activity (30-min)
Step-by-Step Procedure
Write a Program to Read, Write, and Append Data to a File Using the
fsModule (15 min):Step 1: Create a file named
fileOperations.js.Step 2: Add the following code:
javascript코드 복사const fs = require('fs'); // Write to a file fs.writeFile('example.txt', 'This is an example file.', (err) => { if (err) throw err; console.log('File created and written to.'); // Read the file fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log('File content:', data); // Append to the file fs.appendFile('example.txt', '\nAppended text.', (err) => { if (err) throw err; console.log('Content appended to file.'); }); }); });Step 3: Run the script:
bash코드 복사node fileOperations.jsExpected Output:
File is created and written to.
Content is read from the file and displayed.
Additional content is appended to the file.
Create a Simple HTTP Server Using the
httpModule (15 min):Step 1: Create a file named
httpServer.js.Step 2: Add the following code:
javascript코드 복사const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the Home Page'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('This is the About Page'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); });Step 3: Run the script:
bash코드 복사node httpServer.jsStep 4: Test the server:
Visit
http://localhost:3000/for the Home Page.Visit
http://localhost:3000/aboutfor the About Page.Visit
http://localhost:3000/unknownto test the 404 response.
Last updated