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

160
Views
Leyendo parte del archivo en el nodo

Tengo 2 objetos json dentro de archivos .txt grandes en un entorno de electrones. ¿Cuál es la forma correcta de:

  1. leyendo el primer objeto json en el archivo
  2. ignorando el segundo
  3. repitiendo este comportamiento para cada archivo de forma asíncrona

Así es como accedo a archivos con 1 objeto json dentro:

 async readFile() { try{ await fs.promises.access(filename, fs.constants.F_OK) try { const data = await fs.promises.readFile(`${dir}/${filename}`, 'utf8') let obj = JSON.parse(data) return obj } catch(err) { console.log(err) } } catch (err) { console.log("File Doesn\'t Exist. Creating new file.") fs.writeFile(filename, '', err => { err ? console.log(err) : null }) } }

Pensé en leerlo línea por línea y verificar el primer carácter ':' y el carácter '}', analizar el contenido entre estas líneas y cerrar el archivo. Sin embargo, no funcionará con objetos anidados.

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

0

Usaría un flujo de lectura para leer fragmentos y luego verificaría carácter por carácter hasta que tenga un objeto, definido como el número de { === }. Algo como esto:

 const fs = require("fs"); async function read() { //TODO: add check for fileexists const obj = await findFirstJsonObjectFromFile("file.json"); //TODO: convert to json object and return console.log(obj); } const findFirstJsonObjectFromFile = async fileName => { return new Promise(resolve => { const fileStream = fs.createReadStream(fileName, { highWaterMark: 60 }); const jsonString = []; let started = 0; fileStream .on("error", () => resolve(jsonString.join(""))) .on("end", () => resolve(jsonString.join(""))) .on("data", chunk => { for (let i = 0; i < chunk.length; i++) { const a = String.fromCharCode(chunk[i]); jsonString.push(a); if (a === "{") { started++; } else if (a === "}" && started === 1) { resolve(jsonString.join("")); } else if (a === "}") { started--; } } }); }); }; //TODO: loop over all files and send as parameter read();
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!