Create a Journal App in Browser

In this post we are going to do some simple DOM manipulation and take text input and add it to a ul as a li in the browser. We are going to use Bootstrap 4 for our UI and keep it really simple.

First we want to get a game plan together, so I map out the following for the HTML:

<!--Input and Submit Button -->
<!-- Output Journal Entries as list items -->

And the following for the JS:

//add event listener to listen for either enter keypress or submit button clicked
//id="entryInput"
//id="entryInputButton"
// on enter or submit button clicked we want li element to be added to the top
// of the list so most recent journal entries are at the top
//id="journalUL" 
// on enter or submit button clicked we want li element to be added to the top
// of the list so most recent journal entries are at the top
//create an html element and add it to the DOM 

The first thing I do is head over to getbootstrap.com and copy the JS and CSS CDN code.

Then I add copy the button components from: https://getbootstrap.com/docs/3.4/components/#btn-groups

Next it is time to add a place for the journal entries:

<ul id="journalUL">
</ul>

Then I start in on the javascript:

document.getElementById("entryInputButton").addEventListener("click", function() {const inputElement = document.getElementById('entryInput');
let entry = `(${Date.now()}) - ${inputElement.value}`;
let newLi = document.createElement("li");
newLi.innerText = entry;
  document.getElementById("journalUL").prepend(newLi);
  inputElement.value = "";
});

It turned out to be a single event listener.

This was a good refresher, but it seems like it is time to turn it up a notch.

Thanks for your time, and stay tuned.

Create a Command Line Journal App in Node

Tracking our thoughts. It is something we all think about doing at one time or another. Myself I have tried to start a journal and keep up with it countless times. I usually get several days in to a couple weeks then move on to something else.

I don’t think that is such a bad thing. Sometimes you need to think something out over a couple days and then you are good to go.

So today we are going to build a Command Line Journal App. You can run it from your powershell terminal and it will check for a journal.txt file and if no such file exists it will create one and take entries until you tell it to stop or quit.

Let’s get started!

First we need to dependencies fs and readline:

const fs = require('fs');
const readline = require('readline');

Our journal is going to contain a couple of different parts with multiple tasks in each part, so I want to take a sec to add some comments that will serve as a plan for the application.

// create a variable for file path
// prepare rl variable
// check if a file exists
// if file exists open the file 
// // open the file 
// Ask for users name and then write name in Journal by template string
// get input from user
// Create a file by writing the word journal to the file
// if input is exit or quit then rl.close

So we want to try to open an existing file and if we throw an error (the file doesn’t exist) then we want to alert the user of the error, let them know we are creating a file and then create a file with the text “Journal inside:

let textIn ;
try {
 // open the file 
 textIn = fs.readFileSync(FILEPATH, 'utf-8');
} catch (err) {
  console.log('Error', err);
  console.log('Creating File...');
  // Ask for users name and then write name in Journal by template string
 //TODO at Later Date
  // Create a file by writing the word journal to the file
  fs.writeFileSync(FILEPATH, 'Journal');
}

Now that we have a file open and stored in a variable we have to accept some input from the user and write it to the file. I initially try to use a while loop to continue to take input from the user and write to file until the entry is quit, but this created a loop that crashed VS Code.

I found an article on stack over flow where a user recommends using recursion to solve this issue.

The other suggestions looked interesting but I wasn’t able to wrap my head around them at this time. I copied the recursion code to my file and commented out my old erroneous code. Then I copied what was necessary from my code replacing the example code to come up with the following code:

var recursiveAsyncReadLine = function (textIn) {
  rl.question('Journal Entry: ', function (entry) {
    if (entry == 'exit' || entry == 'quit') //we need some base case, for recursion
      return rl.close(); //closing RL and returning from function.
    fs.writeFileSync(FILEPATH, `${textIn} \n (${Date.now()}) - ${entry}`);
    recursiveAsyncReadLine(); //Calling this function again to ask new question
  });
};

recursiveAsyncReadLine(textIn); 

Finally, we need to exit the app on “close” and output the file to the console for all to see.

rl.on("close", function() {
  console.log("\n Journal thus far... \n");
  console.log(fs.readFileSync(FILEPATH, 'utf-8'));
  process.exit(0);
});

That did it! We now have a command line app that will read a file or create one if journal.txt doesn’t exist and then ask for input from the user and will write each entry to a file until the user types “quit” or “exit” into the prompt.

Check out the video, like, subscribe and leave a comment. Thanks for your time!

Read Input and Write File With Node

Yesterday, I learned how to read from a file. Today, I wanted to learn the natural extension of yesterday’s lesson and learn to write to a file! Along the way, I decided I needed to get some input from the command line so I could write dynamic info to my Welcome.txt file.

Just like yesterday, we will be using the fs module bundled with Node. So we start out with

const fs = require('fs');

Next we want to write something new to the file. (WARNING: If you don’t read your file first and append the new data to the old you will overwrite your entire file)

fs.writeFileSync('./Welcome.txt', `\n (${Date.now()}) - Test001`);

Ok, now we just read the file and output it to the console.

console.log(fs.readFileSync('./Welcome.txt', 'utf-8'));

In order to not overwrite your whole file like I did you need to first read in your old file and then prepend that to your string template literal.

const textIn = fs.readFileSync('./Welcome.txt','utf-8');
fs.writeFileSync('./Welcome.txt', `${textIn} \n (${Date.now()}) - NewText001`);

Each time I wanted to add something new to the file I had to change my source code and that was obviously not ideal. So we need a way to input some new text for our file from the command line and luckily we found the readline module. You can import it with the following require statement:

const readline = require("readline");

The next thing we needed to do was to setup a rl variable with an object that contains input and output data. We found this in Node’s documentation here: https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/ and it looks like this:

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

Next we use the rl variable’s question method to set up a question and then pass the input from the command line into a callback function where we write that text input to our file. Inside this callback function we use the rl variable’s close method to stop the input stream. This looks like the following:

rl.question('Journal Entry for Today: ', function(entry) {
  fs.writeFileSync('./Welcome.txt', `${textIn} \n (${Date.now()}) - ${entry}`);
  rl.close();
});

Finally we want to stop the process and return to the command prompt using the rl variables on method where we pass the phrase “close” and a callback function where we log the resulting text file in the console and then use process.exit to kill the program.

rl.on("close", function() {
  console.log("\nBYE BYE !!!");
  console.log(fs.readFileSync('./Welcome.txt', 'utf-8'));
  process.exit(0);
});

Viola! There we have it.

We read input from the command line and we wrote that input to a file. Tomorrow we may try to loop this until we decide to quit or something else. Not sure. Thanks for reading and following along. Message me on twitter @jasonmziegler

Reading a File Javascript

So you want to read a file from Javascript?

Really? ok, well, I do, too.

Why because I have a larger goal of being a Javascript master. I want to “spin up” apps and create fun things that will help me and help the world. I believe I can do it. This begins my journey.

Let’s go!

So first thing I create a file in my Visual Studio Code IDE.

I call mine deadset001_readfile.js

Here is where we will write the code to read the txt file.

Next I create a text file to read.

I call it Welcome.txt and write Welcome to Deadset on Success Coding! Thank you for watching.

First thing we want to do is to require the fs module. This is built in to node so you don’t have to install anything.

Do you not have Node.js? Well, go get it. No we won’t wait.

So type in to your code editor

const fs = require('fs');

Now we have access to a variable that contains all of the filesystem methods that we need to read a file from our disk.

Let’s Use it!

const welcome = fs.readFileSync('./Welcome.txt', 'utf-8');

ok, that’s it! we did it.

We read a file using javascript.

What? You don’t believe me?

Ok, I will prove it.

On the next line, type the following:

console.log('The file contains the following text: ", welcome);

ok, right click on your file in the explorer of VS code and select open in integrated terminal. This will take you to the directory where your file exists. You got Node.js, right?

Great! type into the terminal node filename.js in my case I wrote node ./deadset001_readfile.js

Now hit enter!

You should see the following out put

The file contains the following text:  Welcome to Deadset on Success Coding! Thank you for watching. 
Read a File Using Node