Home Logic LAMP Stack Blog

NodeJS Project 1: rl

Step 8: Edit fileMaker.js

I want to keep the changes I made to cherry.JSON. Let's edit our fileMaker.js.

candy@cc:~/myFiles$ vim fileMaker.js

Let's edit fileMaker.js to take command line input to determine file location. Instead of hardcoding 'var file = 'cherry.json', we will enter a value for file on the command line. The new file will look like this:


var fs = require('fs'); // file system
'use strict'; // prevents many common coding mistakes
const readline = require('readline');

// Command Line Interface
const rl = readline.createInterface({
 input: process.stdin,
 output: process.stdout
});

// JavaScript Object
var data = { name: 'Candy',
            title: 'Commander'};

// Command Line Prompt: enter file location
rl.question('Good day sir!  What file location would you like for your JSON file?', function(file) {
  /* write file, with the file location (command line input)
         passed in */
  fs.writeFile(file, JSON.stringify(data), function (err) {
    if (err) throw err; // if error, return error
    else {  // if sucessful
      // Display message in terminal
      console.log(`Thank you for using me today!  Hope to see you again soon! File: ${file} saved!`);
      // read the file just created
      fs.readFile(file,function (err, data) {
        if (err) throw err;  // if error, return error
        else { // if sucessful
          var object = JSON.parse(data); // JSON string -> JS Object
          console.log(object); // print
        }
      });
   }
 });
  rl.close();
});
        

Step 9: Save

Save the updated fileMaker.js and exit vim. esc to command mode then ZZ

Step 10: Run Code

candy@cc:~/myFiles$ node fileMaker.js


Output should look something like this:

candy@cc:~/myFiles$~/myFiles$ node fileMaker.js
Good day sir! What file location would you like for your JSON file?jellybean.json
Thank you for using me today! Hope to see you again soon! File: jellybean.json saved!
Fiverr

Step 10: Check JSON

Now let's check for the JSON file:

candy@cc:~/myFiles$ ls
cherry.json fileMaker.js jellybean.json
candy@cc:~/myFiles$ vim jellybean.json

Final Step

Now edit the file maker, so the user enters:
1) File Location
2) File Data

Questions?

If you have any questions about the homework, Tweet me! Make sure to upload your code to GitHub or GitLab, so you can include the link.

Previous Lesson | Next Lesson