Terminal

In this article, we will build together a simple command-line application using NodeJS.

We will make a very original (not really) ToDo application. In this application, you will be able to create a todo, update todos and remove todos. We will use a file-based storage, meaning our todos will be stored in a file. Considering the size of the project, I believe a database is not necessary.

What do we need?

We will only use the tools that NodeJS provides us out of the box. No packages, no npm to worry about.

We won’t need much actually. To interact with the command-line, we will use the process object. It is a global object that allows us to read and control the current NodeJS process. You can find more information about this here : Node Process Docs .
Process is a global, meaning it’s always available, no need to require() it.

Next, because we will implement a file-based storage, we need to read and write to a file. NodeJS gives us the filesystem module, known as ‘fs’. We do need to require it.

And, that’s all we need. The rest of the logic will be handle by regular Javascript, let’s get started!

1) Files

First, let’s create a directory. Go to your terminal and type

mkdir <nameOfYourNewFolder>

and press enter. Now, type

cd <nameOfYourNewFolder>

and then:

touch server.js todos.txt

Great, we have our files now.
Let’s open our text editor and create some todos in our todos.txt.

Here is my todos.txt:

Buy clothes|Feed the cat

Note: To differentiate each todo, I chose to separate them with a pipe character. This choice is totally up to you, choose whatever character you feel is appropriate.

2) Read Todos from file

Awesome, now how do we read those todos from our todos.txt and display them in the terminal?
Open server.js and type this.


process.stdin.setEncoding('utf-8');
const fs = require('fs');

//Read todo from file and display them
let todos = getTodosFromFile();
displayTodos(todos);

function getTodosFromFile(){
    let todos = fs.readFileSync('todos.txt', {encoding: 'utf-8'});
    return todos.split('|');
}

function displayTodos(todosArray){
    console.log('\n\nHere are your todos: \n\n');
    for(let i = 0; i < todosArray.length; i++){
    console.log(i + ') ' + todosArray[i]);
}

console.log('\n');
displayInstructions();
console.log('\n');
}

function displayInstructions(){
    console.log('Type quit to exit. Type create <todo> to add a new todo.\n',
    'Type update <index> <todo> to update a todo.\n',
    'Type delete <index> to delete a todo.');
}

Let me explain: the first line sets the encoding for the terminal, here utf-8(in this case, stdin is our terminal).
Next, we require our fs module.

Next, we have a few functions.

The first function getTodosFromFile retrieves the content of our todos.txt. To achieve this, we use the fs.readFileSync function. It takes 2 parameters, the path of the file we want to read, and an object of options. The file is in the same directory as server.js, so we just type ‘todos.txt’. For the options, I specified the encoding {encoding: ‘utf-8’}. Now, this fs.readFileSync returns a string. But, I decide to split this array with the ‘|’ character. That allows me to know where a todo string stops and starts.

Note: If you use a different character than ‘|’ , you’ll have to replace the appropriate character in the split method.

Awesome, we are now in possession of an array of todos. Let’s show them with the displayTodos function. As you can see, this function takes the array of todos and iterate through them. I added a few newlines characters (\n) for clarity.

The displayInstructions function gives the user informations about how to interact with the application.

Amazing, so let’s see how this works.
Go to your terminal and type

node server.js

And here you see your todos:


Here are your todos:
0) Buy clothes
1) Feed the cat

Type quit to exit. Type create <todo> to add a new todo.
Type update <index> <todo> to update a todo.
Type delete <index> to delete a todo.

Now, let’s add the different commands to create, update and delete todos.
We’ll start with creating.

3) Create todo

Right now, if you tried to type something in the console, nothing happens. You can only kill the process with Control + C. Why? Because we need to tell our process.stdin (terminal) what to do when we enter data.
In our displayInstructions function, you can see that we have 4 words that will be used as commands: quit, create, update and delete. Again, those are totally arbitrary.

So, our program needs to identify when the user enters data to the terminal, then our program needs to know if the text entered contains a special command. If the answer is yes, it triggers some actions depending on the command.

First things first, making our terminal listens to the data we type. To do this, we add this code:

process.stdin.on('data', (text)=>{
// our logic will go here
});

Each time we send data to the terminal, meaning each time we press Enter, the program will run the callback. The text parameter will be the string that you typed in the terminal. It will be a string because we set the encoding to ‘utf-8’ on the first line, remember?

Now, we need to now if the first word of the text is in fact a command. If we use a split method on the string and a switch statement, we can handle this problem like this:

process.stdin.on('data', (text)=>{
//split the string at the spaces
let textAsArray = text.split(' ');
let command = textAsArray[0];

switch(command){
    case 'create':
        //create Todo
        break;
    case 'update':
        //update Todo
        break;
    case 'delete':
        //delete Todo
        break;
    case 'quit\n':
        //exit program
        break;
    default:
        console.log('Unknown command.');
        displayInstructions();
    }
});

Each command has its own logic. If the command is not create, update, delete or quit, we use the displayInstructions function to help the user.

Note: You may notice the newline(\n) character after ‘quit’. When you type enter, the terminal seems to add this character automatically. Because the other commands needs additional input to their logic, if you just type ‘create’ or ‘delete’ or ‘update’, it will trigger the default case (because the terminal will add the newline character by default).

Very well, let’s write our logic for creating a Todo. The ‘create’ case will look like this:

case 'create':
    // Get todo text and update todos.txt
    let todoText = textAsArray.slice(1).join(' ');
    fs.appendFileSync('todos.txt', '|' + todoText);
    let todos = getTodosFromFile();
    displayTodos(todos);
    break;

First, we take away the command from the text. Remember, we split the string before the switch statement. So everything after the command is the body of our Todo. So we join the rest of the array with spaces.
Now, here is the fun part. We have our Todo as a string. We need to add it to our file todos.txt. To achieve this, we use fs.appendFileSync. It takes 2 parameters, the path of the file we want to write to, and the text we want to write. Notice that I add the ‘|’ character before the text of the Todo to help use differentiate todos in the future. After that, we use two functions that we already wrote earlier, getTodosFromFile and displayTodos. Now, after running this program, you will see your todos.txt updated and your new todo added in your terminal.

Note: Careful with the function you use to write to a file. Certain functions like fs.writeFileSync will replace the content of the file and not append. You can get more informations about the fs functions here: Node fs Docs

4)Update Todo

Awesome, now we can add todos to our little program. Let’s move on to updating.
If you read the instructions, you saw that the update command needs to be followed by the index of the todo you want to update, then by the new text of the todo. This means that we have to slice our array a bit more to retrieve the index. Here is how we could put this in place:

Add this inside the ‘update’ case:


case 'update':
    let indexUpdate = textAsArray[1];
    let newTodoText = textAsArray.slice(2).join(' ');
    if(isNaN(indexUpdate)){
        console.log('You must enter the index of the todo you want to update.');
    }else{
        updateTodo(indexUpdate, newTodoText);
    }
    break;

And here is the updateTodo function:

function updateTodo(index, todo){
    let todos = getTodosFromFile();
    if(index > todos.length -1 || index < 0){
        console.log('Index out of range');
        return;
    }
    todos[index] = todo;
    let updatedTodos = todos.join('|');
    fs.writeFileSync('todos.txt', updatedTodos);
    console.log('\nTodo Updated! \n ');
    displayTodos(todos);
}

Alright, let me break this down a bit. So we know the index is going to be at the second position in the textAsArray. This means everything after the index is the body of the updated Todo. We need to make sure the index is actually a number. If it is, we run the updateTodo function.
This function retrieves the todos first so we are up-to-date with the file. Next, we control that the index is in range. If it is, we update the correct todo. Then, as we did before with create, we write the new todos in our file. Finally, we display the new set of todos.

5)Delete Todo

We’re almost there! We now need to implement a way to delete a todo. To do this, we use the delete command followed by the index of the todo. Here is how the ‘delete’ case will look like:


case 'delete:
    let indexDelete = textAsArray[1];
    if(isNaN(indexDelete)){
        console.log('You must enter the index of the todo you want to delete.');
    }else{
        deleteTodo(indexDelete);
    }
    break;

And here is the deleteTodo function:

function deleteTodo(index){
    let todos = getTodosFromFile();
    if(index > todos.length -1 || index < 0){
        console.log('Index out of range');
        return;
    }
    todos.splice(index, 1);
    let updatedTodos = todos.join('|');
    fs.writeFileSync('todos.txt', updatedTodos);
    console.log('\nTodo Deleted!\n');
    displayTodos(todos);
}

Just like the update case, we retrieve the index and make sure it is a number. Then we call the deleteTodo function. We get up-to-date with the current todos and we make sure the index is not out of range. Then, a classic splice method on the todos array deletes the targeted todo. We join the array with our pipe ‘|’ character and write it to our file. Finally, we can display our todos.

6) Exit the program

Yeah! We can add, delete and update todos. We just need one more little thing: a way to exit the program. Now, if you know how to use the terminal, you will do control + C.But, our users may not know this trick. So we added the quit command. To do this, we add this logic to the ‘quit\n’ case:

case 'quit\n':
    console.log('Good Bye!');
    process.exit();

As you might have guessed, process.exit() kills the current process.

And there it is. We have a fun command-line application. You can run it with node server.js in your terminal.
You can get the full code here :
Code on GitHub

I hope everything was clear. Feel free to ask questions and share!
Have a nice day!

Read more