Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!