Creating the simplest todo app with NodeJS

Node-JS, Express, To-do App
Node-JS, Express, To-do App

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It make it possible to run JavaScript on the server side, creating web applications with server-side rendering. One of the most popular web frameworks for Node.js is Express. It is a minimalist web framework that provides features for building web applications, APIs, and middleware.

This article will teach us how to build a simple to-do application using Node.js with Express. We will cover the following topics:

  • Setting up a Node.js project with Express
  • Defining routes and handling HTTP requests
  • Rendering HTML templates with EJS
  • Storing data with a JSON file

Prerequisites

To follow along with this tutorial, you should have the following installed on your system:

  • Node.js and npm (the Node.js package manager)
  • A text editor (such as Visual Studio Code)
  • It would help if you had a basic understanding of Node JS.

Creating a Node.js Project with Express

To create a Node.js project with Express, we will use the express-generator, a command-line tool that generates a basic Express app.

Open a terminal and paste the command below to install the express generator globally:

npm install -g express-generator

Next, navigate to the directory where you want to create your project and run the following command to generate the Express app:

express todo-app

This will create a new todo-app directory with the basic structure of a Node.js app with Express.

Now, navigate to the project directory and install the dependencies by running the following command:

npm install

This will install all the dependencies specified in the package.json file, including Express.

Defining Routes and Handling HTTP Requests

In Express, a route combines an HTTP method and a URL path that defines the app's behavior. To define a route, we use the app.METHOD() function, where METHOD is the HTTP method (such as GET, POST, PUT, etc.), and app is an instance of the Express app.

For example, to define a route that handles GET requests to the / URL path, we can use the following code:

app.get('/', (req, res) => {
  // code to handle the request and send the response
});

The req object represents the HTTP request, and the res object represents the HTTP response. We can use these objects to access information about the request and send a response back to the client.

In the todo-app directory, open the routes/index.js file and replace the code with the following:

const express = require('express');
const router = express.Router();

/* GET home page. */
router.get('/', (req, res) => {
  res.render('index', { title: 'To-Do App' });
});

module.exports = router;

This code defines a route that handles GET requests to the / URL path and renders the index view with the title variable set to 'To-Do App'.

Rendering HTML Templates with EJS

Now let's talk about rendering HTML templates with EJS.

EJS is a templating engine that allows us to embed JavaScript in HTML files. It allows us to create reusable HTML templates and pass data to them to generate the final HTML output.

You need to install the ejs module first before proceeding. To do this, open your terminal and paste the code below.

npm install ejs

When done installing, open the server again by running npm start.

To use EJS with Express, we need to set the view engine setting to ejs and specify the directory where the view files are located. Open the app.js file and add the following lines of code:

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
NOTE: The express-generator uses jade templating engine. You can delete the files in the views directory, as we will use ejs instead.

Next, create an index.ejs file in the views directory with the following content:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1><%= title %></h1>
</body>
</html>

The <%= %> tags are used to output the value of a variable. In this case, we output the title variable passed from the route handler.

Now, if you start the app by running the npm start command in the terminal and visit http://localhost:3000 in your browser, you should see a page with the heading "To-Do App".

Storing Data with a JSON File

To store data in our to-do app, we can use a simple JSON file. First, create a data.json file in the root directory with the following content:

{
  "tasks": []
}

This file will store an array of tasks.

Next, create a route handler that reads and writes to this file. Add the following code to the routes/index.js file:

const fs = require('fs');  // move this to the top of the file.

/* GET tasks. */
router.get('/tasks', (req, res) => {
  fs.readFile('data.json', (error, data) => {
    if (error) {
      res.status(500).send(error);
    } else {
      res.send(JSON.parse(data));
    }
  });
});

/* POST task. */
router.post('/tasks', (req, res) => {
  fs.readFile('data.json', (error, data) => {
    if (error) {
      res.status(500).send(error);
    } else {
      const todo = JSON.parse(data);
      todo.tasks.push(req.body)
      fs.writeFile('data.json', JSON.stringify(todo), (error) => {
        if (error) {
          res.status(500).send(error);
        } else {
          res.send(todo);
        }
      });
    }
  });
});

The /tasks route handles GET and POST requests. The GET request returns the array of tasks stored in the data.json file, and the POST request adds a new task to the array and writes it back to the file.

To test these routes, we can use a tool like Postman.

Testing the routes with Postman

Let's see how to test the /tasks route using Postman.

Open Postman and create a new request. Select the GET method and enter the URL http://localhost:3000/tasks. Send the request and you should see an empty array in the response body.

Next, create another request with the POST method and the same URL. In the body of the request, select the raw option. Also, change the dropdown to JSON instead of Text.

JSON

Enter the following JSON data:

{
  "name": "Task 1",
  "done": false
}

Send the request, and you should see the array with the new task in the response body.

Conclusion

This article taught us how to create a simple to-do app with Node JS and Express. We covered the following topics:

  • Setting up a Node.js project with Express
  • Defining routes and handling HTTP requests
  • Rendering HTML templates with EJS
  • Storing data with a JSON file

This is just the beginning of what you can do with Node.js and Express. You can explore other features of the framework, such as middleware, routing, and error handling, to build more complex and feature-rich applications.

If you have any questions, drop them in the comments for clarification.

Thanks for reading!

If you enjoy our content, please consider buying us a coffee to support our work:

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.