node.jsfile

NodeJS: how to read (at most) the first N bytes from a file?


In NodeJS, what is a concise, robust, and elegant way to read at most the first N bytes from a file?

Ideally without installing external packages. Maybe involving async iterators which seem to be new (non-experimental) since NodeJS 12?

Bonus: how do I read the first N characters, providing a specific codec (such as utf-8)?

Edit: based on my Internet research the answer to this indeed rather basic question is far from obvious, which is why I ask. I know how to do this in other language environments, and I am new to the NodeJS ecosystem.


Solution

  • I have been using the following approach for a while now in NodeJS 12 (with TypeScript):

    async function readFirstNBytes(path: fs.PathLike, n: number): Promise<Buffer> {
      const chunks = [];
      for await (let chunk of fs.createReadStream(path, { start: 0, end: n-1 })) {
        chunks.push(chunk);
      }
      return Buffer.concat(chunks);
    }