Soy nuevo en node.js y estoy luchando con este problema. No entiendo por qué mi salida es
ciao data datay no
data data ciaoeste es mi codigo
fs.readdir("sender", (err, files) => { if (err) { throw err; } const path = __dirname + "/sender/"; let rawdata = fs.readFileSync(path + "data.json"); var data = JSON.parse(rawdata); files.forEach((file) => { fs.stat(path + file, (err, stats) => { if (err) { throw err; } if (data[file]["size"] != stats.size) data[file]["size"] = stats.size; if (data[file]["time"] != stats.mtime.toISOString()) data[file]["time"] = stats.mtime.toISOString(); console.log("data"); }); }); console.log("ciao"); });He leído que foreach no es asíncrono, por lo que realmente no entiendo por qué se invierte la salida.
forEach no es asíncrono. Pero la operación que está realizando en la devolución de llamada forEach , fs.stat , es asíncrona.
Entonces, lo que está haciendo su código es comenzar una serie de operaciones fs.stat (parece que dos), luego registrar ciao , luego, cuando se completa cada una de esas operaciones fs.stat , está registrando data .
En su lugar, podría usar la API del sistema de archivos basada en promesas y usar async / await ; ver comentarios:
const {readdir, readFile, stat} from "fs/promises"; // This version of `readdir` returns a promise fs.readdir("sender") .then(async files => { // Use an `async` function as the fulfillment callback const path = __dirname + "/sender/"; // Await the promise from `readFile` (no need to use `readFileSync`) const rawdata = await readFile(path + "data.json"); const data = JSON.parse(rawdata); // Wait for all operations to complete (they run in parallel) await Promise.all(files.map(async file => { // Get the stats (again, awaiting the promise) const stats = await stat(path + file); // Update the entry for the file. const entry = data[file]; if (entry.size != stats.size) { // (There's no point to this comparison, just do the assignment) entry.size = stats.size; } if (entry.time != stats.mtime.toISOString()) { // (Again) entry.time = stats.mtime.toISOString(); } console.log("data"); })); // Since this is after the `await` on the promise from `Promise.all`, it doesn't run until all // of the promises `Promise.all` was waiting on have been fulfilled console.log("ciao"); }) .catch(error => { // ...log/handle error... });