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.
Initialize your project:
mkdir todo-backend cd todo-backend npm init -y npm install express body-parser
Create a file named
server.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}`); });
Create a
todos.json
file:Create a
todos.json
file in the same directory as yourserver.js
. This file will initially be an empty array:[]
.[]
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.
ย