How to Build Todo List Application using Node.js?

This tutorial will teach you the step-by-step guide to creating a Todo List Application using Node.js.

A Todo List Application can be used to manage day-to-day tasks.

Making a Todo List Application using Node.js involve many programming concepts such as templating using EJS, getting form data, sending data to HTML file, etc, which helps you to sharpen your Node.js skills.

Also Read: Build a Video Streaming Application in NodeJS

Features of a Todo List Application

The following are the features of the Todo List Application.

  1. Display Task
  2. Add Task
  3. Delete Task

Creating a Todo List Application

Below is the step-by-step guide to creating a Todo List Application using Node.js.

Project Setup to Build a NodeJS Todo List Application

Create a project folder then locate the folder in the terminal and execute the below command to initiate NPM.

npm init -y

NPM stands for Node Package Manager used to install different NodeJS packages. We have a separate tutorial on NodeJS NPM if you want to read.

Install Modules: Install Express and EJS modules inside the project folder using the below command.

npm i express ejs

Project Structure

The project contains a JavaScript file “app.js”, where we will write code for creating the Todo List Application, a package.json and package-lock.json file which includes the information regarding the modules installed in our project, and a node_modules folder which contains the actual module installed inside our projects. 

Folder Structure

Writing Code to Build a NodeJS Todo List Application

Import Express: Inside the “app.js” file, import the Express module and create an instance “app” using it.

const express = require("express");

const app = express();

Import EJS: Use EJS as middleware for the view engine.

app.set("view engine", "ejs");

Now, it is required to create a folder with the name “views”, which contains the HTML file, the HTML files require to have the extension “.ejs” rather than “.html”.

Create Todos Array: Create an array containing predefined tasks to showcase to the user.

const todos = [{
        todoId: "1",
        todoTask: "Code",
    },
    {
        todoId: "2",
        todoTask: "Sleep",
    },
    {
        todoId: "3",
        todoTask: "Coffee",
    }
];

Getting Form Data: In the upcoming step, we have to create a functionality to enter data in a form to add a task. Below is the code to use express middleware in order to handle the incoming form data.

app.use(express.json());       
app.use(express.urlencoded({extended: true})); 

Render the Todo Tasks

Use the get() method to create a home route, represent “/” which is the application’s default page, and then define the functionality to send the todos array to an HTML file “index.ejs”.

app.get("/", function (req, res) {
    res.render("index", {
        data: todos,
    });
});

Inside the “index.ejs” file we have to fetch every single element from the array. For this, we can use a loop to iterate through the array, select every single element one by one, and insert it as table data in a row of the HTML table.

index.ejs

Add Task to the List

To add a task to the todos array, we have to set up a form inside the “index.ejs” file.

<form action="/" method="POST">
    <input type="text" name="todoTask" placeholder="Enter Task">
    <button type="submit">Add</button>
 </form>

To handle the form data, we have to create a new route in which we fetch the form data and push it to the todos array.

app.post("/", (req, res) => {
    const inputTodoId = todos.length + 1;
    const inputTodoTask = req.body.todoTask;

    todos.push({
        todoId: inputTodoId,
        todoTask: inputTodoTask
    });

    res.render("index", {
        data: todos,
    });
});

Delete Task from the List

Create a new form with a button to delete the task when clicked. 

<form action="/delete" method="POST">
       <input type="hidden" name="todoId" value="<%= element.todoId %>">
       <input type="hidden" name="todoTask" value="<%= element.todoTask %>">
       <button class="delete" type="submit">❌</button>
</form>

This form gets attached to every task.

Delete Form

You can see that the form has the task id which we will use to know for which task the button gets clicked in order to delete it from the todos array.

Handle the form inside the “app.js” file to delete the task from the todos array.

app.post("/delete", (req, res) => {
    var requestedtodoId = req.body.todoId;
    var j = 0;
    todos.forEach((todo) => {
        j = j + 1;
        if (todo.todoId === requestedtodoId) {
            todos.splice(j - 1, 1);
        }
    });
    res.redirect("/");
});

Finally, create a port to test our application on browsers using the listen() method and pass the 3000 port as an argument.

app.listen(3000, (req, res) => {
    console.log("App is running on port 3000");
});

Complete Code for a Todo List Application in NodeJS

app.js

const express = require("express");

const app = express();

app.set("view engine", "ejs");

const todos = [{
        todoId: "1",
        todoTask: "Code",
    },
    {
        todoId: "2",
        todoTask: "Sleep",
    },
    {
        todoId: "3",
        todoTask: "Coffee",
    }
];

app.use(express.json());       
app.use(express.urlencoded({extended: true})); 

app.get("/", function (req, res) {
    res.render("index", {
        data: todos,
    });
});

app.post("/", (req, res) => {
    const inputTodoId = todos.length + 1;
    const inputTodoTask = req.body.todoTask;

    todos.push({
        todoId: inputTodoId,
        todoTask: inputTodoTask
    });

    res.render("index", {
        data: todos,
    });
});

app.post("/delete", (req, res) => {
    var requestedtodoId = req.body.todoId;
    var j = 0;
    todos.forEach((todo) => {
        j = j + 1;
        if (todo.todoId === requestedtodoId) {
            todos.splice(j - 1, 1);
        }
    });
    res.redirect("/");
});

app.listen(3000, (req, res) => {
    console.log("App is running on port 3000");
});

Run the Application

The application code is written in a single file “app.js” that runs on executing the below command in the terminal.

node app.js

Open the Application

Enter the below URL inside the search bar of a web browser to open the application.

http://localhost:3000/

Output

Output

Summary

In this tutorial, we have explained the steps to make a Todo List Application using Node.js. A Todo List Application is used to keep track of day-to-day tasks by providing the feature of adding and deleting tasks frequently. Building Todo List Application makes you demonstrate your Node.js programming skills as it covered the concepts like server setup using express, templating using EJS,  how to perform the CRUD option on an array, etc.

Reference

https://expressjs.com/en/resources/middleware/body-parser.html

https://ejs.co

Aditya Gupta
Aditya Gupta
Articles: 94