Simple Todo App Backend CRUD with fs module

Simple Todo App Backend CRUD with fs module

ยท

2 min read

Certainly! Below is a simple TODO app backend using Node.js, Express, and the fs (file system) module. This example uses a JSON file to store the TODOs. Keep in mind that using a database like MongoDB is typically recommended for a production environment.

Buy Me A Coffee

  1. Initialize your project:

     mkdir todo-backend
     cd todo-backend
     npm init -y
     npm install express body-parser
    
  2. Create a file namedserver.js:

     const express = require('express');
     const bodyParser = require('body-parser');
     const fs = require('fs/promises');
     const path = require('path');
    
     const app = express();
     const PORT = 3000;
    
     app.use(bodyParser.json());
    
     // Set up routes
     app.get('/todos', async (req, res) => {
       try {
         const data = await fs.readFile(path.join(__dirname, 'todos.json'));
         const todos = JSON.parse(data);
         res.json(todos);
       } catch (error) {
         res.status(500).json({ error: 'Internal Server Error' });
       }
     });
    
     app.post('/todos', async (req, res) => {
       try {
         const data = await fs.readFile(path.join(__dirname, 'todos.json'));
         const todos = JSON.parse(data);
         const newTodo = { id: Date.now(), text: req.body.text, completed: false };
         todos.push(newTodo);
         await fs.writeFile(path.join(__dirname, 'todos.json'), JSON.stringify(todos, null, 2));
         res.json(newTodo);
       } catch (error) {
         res.status(500).json({ error: 'Internal Server Error' });
       }
     });
    
     app.put('/todos/:id', async (req, res) => {
       try {
         const data = await fs.readFile(path.join(__dirname, 'todos.json'));
         let todos = JSON.parse(data);
         const id = parseInt(req.params.id);
         const updatedTodoIndex = todos.findIndex(todo => todo.id === id);
    
         if (updatedTodoIndex === -1) {
           return res.status(404).json({ error: 'Todo not found' });
         }
    
         todos[updatedTodoIndex] = { ...todos[updatedTodoIndex], ...req.body };
         await fs.writeFile(path.join(__dirname, 'todos.json'), JSON.stringify(todos, null, 2));
         res.json(todos[updatedTodoIndex]);
       } catch (error) {
         res.status(500).json({ error: 'Internal Server Error' });
       }
     });
    
     app.delete('/todos/:id', async (req, res) => {
       try {
         const data = await fs.readFile(path.join(__dirname, 'todos.json'));
         let todos = JSON.parse(data);
         const id = parseInt(req.params.id);
         todos = todos.filter(todo => todo.id !== id);
         await fs.writeFile(path.join(__dirname, 'todos.json'), JSON.stringify(todos, null, 2));
         res.json({ message: 'Todo deleted successfully' });
       } catch (error) {
         res.status(500).json({ error: 'Internal Server Error' });
       }
     });
    
     app.listen(PORT, () => {
       console.log(`Server is running on port ${PORT}`);
     });
    
  3. Create atodos.json file:

    Create a todos.json file in the same directory as your server.js. This file will initially be an empty array: [].

     []
    
  4. Run your server:

     node server.js
    

Now you have a simple TODO app backend with CRUD operations using Node.js, Express, and the fs module. Keep in mind that this is a basic example, and in a production environment, you'd typically use a database for better scalability and reliability.

Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย