Skip to content

Code hangs on reading file from tar #173

@0xaa55h

Description

@0xaa55h

Hello, I wrote this simple code:

export async function extractTarEntry(
  tarStream: Readable,
  targetFilePath: string
): Promise<Buffer> {
  const extract: tar.Extract = tar.extract();
  tarStream.pipe(extract);

  let result: Buffer | undefined = undefined;
  for await (const entry of extract) {
    if (result === undefined && entry.header.name === targetFilePath) {
      const chunks: Buffer[] = [];
      for await (const chunk of entry) {
        chunks.push(chunk);
      }
      result = Buffer.concat(chunks);
    }
    entry.resume();
  }
  return result ?? Buffer.from("");
}

export function wrapEntry(fileStream: Readable, filename: string): Readable {
  const pack = tar.pack();

  const entry = pack.entry({ name: filename }, (err) => {
    if (err) {
      pack.destroy(err);
      return;
    }
    pack.finalize();
  });

  fileStream.on("error", (err) => {
    pack.destroy(err);
  });

  fileStream.pipe(
    new Writable({
      write(chunk, encoding, callback) {
        entry.write(chunk, encoding, callback);
      },
      final(callback) {
        entry.end(callback);
      },
    })
  );

  return pack;
}
test("Tar writing and reading", async () => {
  const stream = wrapEntry(
    Readable.from("Hello, World!"),
    "/data/server.properties"
  );
  const result = await extractTarEntry(stream, "/data/server.properties");

  expect(result).toBeInstanceOf(Buffer);
  expect(result.toString()).toBe("Hello, World!");
});

but the issue im getting is that the code hangs in extractTarEntry function, timing out the test. What am I doing wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions