File Reader Challenge
Create a Node.js app that reads from a text file and manipulates the data. This challenge illustrates the need for callbacks, because the fs module requires a callback to receive the data from a file!
Examples
Review the examples here before starting the challenge. Note how fs.readFile works.
Setup (Repl.it)
- Create a new Node.js Repl Project
- In the new project, create a file named .replit
- In the .replit file, add the following text:
run = "node FileReader.js"
Creating Files
- Create a new text file named
TextInfo.txt - Edit
TextInfo.txtso it contains some interesting text - In the same folder as
TextInfo.txt, create a new JavaScript file namedFileReader.js
Preparing to Read Files
Open the FileReader.js file for editing.
- At the top of the file, use the following command to include the File System module
const fs = require('fs'); - Underneath the
require, define a new function namedyellFile - The
yellFilefunction should take two parameters:erroranddataString- For now, simply use
console.login the body of theyellFilefunction to say "here"
- For now, simply use
- Underneath the
yellFilefunction definition, usefs.readFileto read the text file- The
pathargument should be'TextInfo.txt' - The
optionsargument should be'utf-8' - The
callbackargument should beyellFile
- The
- Run the code and make sure "here" appears!
Yelling the File Contents
The yellFile function should take the contents of the text file (as long as it can successfully open the file), and display them to the user in all caps.
- Remove the
console.logfrom the body of theyellFilefunction - If there is an error (stored in the
errorparameter) reading the file, display a message to the user usingconsole.error - If there is NOT an error, convert text from the file (stored in the
dataStringparameter) to all uppercase - Display the uppercase text to the user with
console.log - Run the code to see the text file contents in all caps!
Elmer Fudd Translator
Define a new function named elmerFudd that takes a string and converts it to "Elmer Fudd Speak." Take a look at funtranslations.com/fudd to see it in action. The translation should apply the following changes to the text:
- Replace every 'th' with a 'd'
- Replace every 'r' with a 'w'
- Replace every 'l' with a 'w'
Use the elmerFudd function in the fs.readFile call to hook it up to the text file!
Writing a File Translation
Reference: https://nodejs.dev/learn/writing-files-with-nodejs
Use fs.writeFile to write the file translation into a new file. After the file has been successfully written, write a message to the console telling the user the operation was successful.
Dealing with User Input
Reference: https://nodejs.org/api/readline.html
Use the readline module to receive input from the user. Ask the user for the following information:
- Path to the file to read
- Path to the file to write
- Which function to perform (yelling or Elmer Fudd translation)
Then, use the information the user enters to execute the program.