Student Activity
Student Activity (30-min)
Step-by-Step Procedure
Implement a Simple Callback Function for Reading a File (15 min):
Create a file named
callbackExample.js.Add the following code:
javascript코드 복사const fs = require('fs'); const readFile = (filePath, callback) => { fs.readFile(filePath, 'utf8', (err, data) => { if (err) return callback(err); callback(null, data); }); }; readFile('example.txt', (err, data) => { if (err) { console.error('Error reading file:', err.message); } else { console.log('File content:', data); } });Create a text file
example.txtwith some sample content: "Hello, Node.js!"Run the script:
bash코드 복사node callbackExample.js
Convert the Callback Function into a Promise-Based Function (15 min):
Modify the above code into a new file named
promiseExample.js:javascript코드 복사const fs = require('fs').promises; const readFile = (filePath) => { return fs.readFile(filePath, 'utf8'); }; readFile('example.txt') .then((data) => console.log('File content:', data)) .catch((err) => console.error('Error reading file:', err.message));Run the script:
bash코드 복사node promiseExample.js
Last updated