Student Activity

Student Activity (30-min)

Step-by-Step Procedure

  1. 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.txt with some sample content: "Hello, Node.js!"

    • Run the script:

      bash코드 복사node callbackExample.js
  2. 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