Dev Helpers
← Back

Read part of a file by offset

Read part of a file by offset using Node.js.

Open this example in the interactive library

Source code

import * as fs from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = await fs.mkdtemp(join(tmpdir(), "helpers-"));
const file = join(dir, "note.txt");
await fs.writeFile(file, "build");
try {
  console.log(
    await (async () => {
      const handle = await fs.open(file);
      try {
        const bytes = Buffer.alloc(2);
        await handle.read(bytes, 0, 2, 1);
        return bytes.toString();
      } finally {
        await handle.close();
      }
    })(),
  );
} finally {
  await fs.rm(dir, { recursive: true, force: true });
}

Sample output

ui