unjs / nanotar

📼 Tiny and fast tar utils for any JavaScript runtime!
MIT License
125 stars 7 forks source link

📼 nanotar

npm version bundle

Tiny and fast tar utils for any JavaScript runtime!

🌳 Tiny (~1KB minified + gzipped with all utils) and tree-shakable!

✨ Written with modern TypeScript and ESM format

✅ Works in any JavaScript runtime Node.js (18+), Bun, Deno, Browsers, and Edge Workers

🌐 Web Standard Compatible

🗜️ Built-in compression and decompression support

Installation

Install package:

# npm
npm install nanotar

# yarn
yarn add nanotar

# pnpm
pnpm install nanotar

# bun
bun install nanotar

Import:

// ESM
import {
  createTar,
  createTarGzip,
  createTarGzipStream,
  parseTar,
  parseTarGzip,
} from "nanotar";

// CommonJS
const { createTar } = require("nanotar");

Creating a tar archive

Easily create a new tar archive using the createTar utility.

The first argument is an array of files to archive:

The second argument is for archive options. You can use attrs to set default attributes for all files (can still be overridden per file).

Possible attributes are:

Example:

import { createTar } from "nanotar";

const data = createTar(
  [
    { name: "README.md", data: "# Hello World!" },
    { name: "test", attrs: { mode: "777", mtime: 0 } },
    { name: "src/index.js", data: "console.log('wow!')" },
  ],
  { attrs: { user: "js", group: "js" } },
);

// Data is a Uint8Array view you can send or write to a file

Compression

You can optionaly use createTarGzip or createTarGzipStream to create a compressed tar data stream (returned value is a Promise<Uint8Array> or RedableStream piped to CompressionStream)

import { createTarGzip, createTarGzipStream } from "nanotar";

createTarGzip([]); // Promise<Uint8Array>

createTarGzipStream([]); // RedableStream

Parsing a tar archive

Easily parse a tar archive using parseTar utility.

Example:

import { parseTar } from "nanotar";

// Read tar data from file or other sources into an ArrayBuffer or Uint8Array

const files = parseTar(data);

/**
[
  {
    "type": "file",
    "name": "hello.txt",
    "size": 12,
    "data": Uint8Array [ ... ],
    "text": "Hello World!",
    "attrs": {
      "gid": 1750,
      "group": "",
      "mode": "0000664",
      "mtime": 1702076997,
      "uid": 1750,
      "user": "root",
    },
  },
  ...
]
 */

Parsed files array has two additional properties: size file size and text, a lazy getter that decodes data view as a string.

Decompression

If input is compressed, you can use parseTarGzip utility instead to parse it (it used DecompressionStream internally and return a Promise<Uint8Array> value)

import { parseTarGzip } from "nanotar";

parseTarGzip(data); // Promise<Uint8Array>

Development

License

Made with 💛

Inspired by ankitrohatgi/tarballjs

Published under the MIT License.