NodeJS without frameworks: findById

I’m beginner and trying to make a function findByID with NodeJS and JSON file as a database without frameworks, code:

const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
    const server = http.createServer((req, res) => {
        const urlparse = url.parse(req.url, true);
      if (urlparse.pathname == "/todos" && req.method == "GET") {
          const search = urlparse.search;
          if (search) { 
            const [, query] = urlparse.search.split("?");
            const data = querystring.parse(query);
            todos = todos.filter((todo) =>  todo.id === data.id);
            res.end(JSON.stringify(todos, null, 2));
          }
        }})

When I check with postman for the first time everything is fine.
1st request

When I check the second time in the response window there is an empty array.2nd request

Each request used a different id.

>Solution :

I dont see todos defined so I assume it’s global, this line is then mutating it every request:

todos = todos.filter((todo) =>  todo.id === data.id);

Another thing is if id is unique you could use todos.find to just get the first match.

So instead use a new variable and find:

const todoMatch = todos.find((todo) =>  todo.id === data.id);

Leave a Reply