Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda