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

119
Views
¿Hay alguna posibilidad de generar el método de mapa en una variable como una matriz de objetos?

¡Hola a todos!

Quiero almacenar usuarios en una carpeta como un archivo donde el nombre del archivo es igual a user_id.

 data | - users | - afdcab7e-b595-4a15-be0f-5f0337bd1317.json | - fdfacb7i-bk00-4a15-be0f-5f0337b1d991.json

Cada usuario tiene sus propios datos por ejemplo

 { "_id": "afdcab7e-b595-4a15-be0f-5f0337bd1317", "email": "test1@test.pl", "password": "$2a$12$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC" }
 { "_id": "fdfacb7i-bk00-4a15-be0f-5f0337b1d991", "email": "test2@test.pl", "password": "$2a$12$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC" }

Luego quiero leer el contenido de todos los archivos y colocar los objetos en una matriz temporal.

 exports.indexSignin = (req, res) => { fs.readdir('./data/users', (err, files) => { if (err) console.log(err); const obj = []; files.map((file) => { fs.readFile(`./data/users/${file}`, 'utf-8', (err, data) => { if (err) console.log(err); obj.push(JSON.parse(data)) console.log(obj) }); }); console.log(obj) //There obj is empty but I want an array }); res.render('./index/index'); });

Como resultado, quiero tener una matriz guardada en una variable como esta que se detalla a continuación:

 [ { "_id": "afdcab7e-b595-4a15-be0f-5f0337bd1317", "email": "test1@test.pl", "password": "$2a$12$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC" }, { "_id": "fdfacb7i-bk00-4a15-be0f-5f0337b1d991", "email": "test2@test.pl", "password": "$2a$12$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC" } ]

¿Tiene alguna idea sobre cómo usar los datos mapeados externamente o refactorizarlos de una mejor manera?

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

0

¡Gracias chicos! Resolví mi problema con Tu ayuda.

Aquí hay un ejemplo de trabajo que necesitaba:

 exports.indexSignin = (req, res) => { const readFiles = async () => { try { const path = "./data/users" const files = await readdir(path); const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8")) const contents = await Promise.all(fileAwaits) return contents.map(co => JSON.parse(co)) } catch (err) { throw err; } } readFiles() .then(test => console.log(test)) .catch(err => console.log('Directory not found.')) .finally(() => console.log('Rest of the code...')); res.render('./index/index'); // or IIFY which do the same (async () => { try { const test = await readFiles(); console.log(test); } catch (err) { console.log('Directory not found.'); } console.log('Rest of the code...') res.render('./index/index'); })() };
about 4 years ago · Juan Pablo Isaza Report

0

Este es el mismo código mío que funciona. Espero que eso te ayude.

 const { readdir, readFile } = require("fs/promises"); const readFiles = async () => { try { const path = "./test" const files = await readdir(path); console.log(files) const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8")) const contents = await Promise.all(fileAwaits) console.log(contents.map(co => JSON.parse(co))) } catch (err) { console.error(err) } } readFiles()

Entonces, si desea usar esto dentro de sus controladores de API, cámbielo de la siguiente manera:

 exports.indexSignin = async (req, res) => { try { const path = "./test" // replace path by your own const files = await readdir(path); console.log(files) const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8")) const contents = await Promise.all(fileAwaits) const arrayContent = contents.map(co => JSON.parse(co)) console.log(arrayContent); } catch (err) { console.error(err) } res.render('./index/index'); });
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!