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

1.1K
Vistas
Why file is not filled yet after writing ? [NodeJS] [Filesystem]

I have problem at reading a file just after appending lines in it. It seems that when inserting less than 913742 characters, it's ok, but when inserting more than 914534 characters, the next lines are read as blank lines (the buffer still empty).

import { promises as fs } from "fs";

const filepath = 'any.file';

const readChunk = async (start: number, end: number) => {
  const buffer = Buffer.from("".padStart(end, " "));
  const fd = await fs.open(filepath, "r");
  await fd.read({ buffer, offset: 0, position: start, length: end });
  await fd.datasync();
  await fd.close();
  return buffer.toString();
};

const append = async (line: string) => {
  const fd = await fs.open(filepath, "a");
  await fd.appendFile(chunk);
  await fd.datasync();
  await fd.close();
};

My jest test:

import faker from "faker";

const fakeUser = (): UserDatas => ({
  id: Math.round(Math.random() * MAX_SAFE_INTEGER),
  message: faker.lorem.paragraphs(),
});

const fakeUsers = (count: number) =>
  Array.from({ length: count }).map(fakeUser);

describe("large amount of data", () => {
  it("should accept thousand lines", async () => {
    const instance = getInstance();
    await instance.append(
      fakeUsers(faker.datatype.number({ min: 9000, max: 10000 }))
    );
    expect(await instance.count()).toBeGreaterThan(8000);
  });
});

The output:

  ● BsonFile › large amount of data › should accept thousand lines

    expect(received).toBeGreaterThan(expected)

    Expected: > 8000
    Received:   1364

      178 |         fakeUsers(faker.datatype.number({ min: 9000, max: 10000 }))
      179 |       );
    > 180 |       expect(await instance.count()).toBeGreaterThan(8000);
          |                                      ^
      181 |     });
      182 |   });
      183 | });

The reason why I can not count more 1364 is that the file does not output any data.

Also, I hoped that fd.datasync() would resolve my problem, but it don't: should I let it there? Is this usefull?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the code below you are adding "chunk", but I can't see that you are defining or setting "chunk" anywhere in the code, should it be "line" that is passed to the function? Could this be the problem?

 const append = async (line: string) => { const fd = await fs.open(filepath, "a"); await fd.appendFile(chunk); await fd.datasync(); await fd.close(); };

Should be:

 const append = async (line: string) => { const fd = await fs.open(filepath, "a"); await fd.appendFile(line); await fd.datasync(); await fd.close(); };

I don't understand your test code. What does getInstance() do?

filehandle.datasync() forces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state.

You shouldn't need to run this function to see the data, it's just there to ensure the buffers are flushed so you don't lose data in the event of a power or hardware failure.

See also https://nodejs.org/api/fs.html#filehandledatasync and https://man7.org/linux/man-pages/man2/fdatasync.2.html for more information.

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