Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
tar
✓ import tar from 'tar';
// Or for direct access to methods:
// import { Pack, Extract, Parse } from 'tar'; // Less common if type is 'commonjs'
// const { Pack, Extract, Parse } = tar;
✗ const tar = require('tar');
While Node.js can import CommonJS modules, `tar` is primarily a CommonJS package (`"type": "commonjs"` in package.json). Direct named imports like `import { Pack } from 'tar'` might not work as expected or might require specific Node.js configuration, especially in older versions. The `import tar from 'tar'` then destructuring is a more robust pattern for ESM consumers.
Pack
✓ const tar = require('tar');
const packStream = tar.Pack();
✗ import { Pack } from 'tar';
const packStream = Pack();
The library primarily exposes its methods via the default `require('tar')` object. While ESM `import { Pack } from 'tar'` *might* work in some modern Node.js environments due to interoperability, the documented and most reliable way is to `require` the module and then access its properties.
Extract
✓ const tar = require('tar');
const extractStream = tar.Extract({ path: './output' });
✗ import tar from 'tar';
const extractStream = tar.extract({ path: './output' });
The methods `Pack`, `Extract`, and `Parse` are exposed with PascalCase names. Using `extract` (camelCase) will result in a `TypeError` as the method does not exist. Ensure correct capitalization.
This quickstart demonstrates how to programmatically create a tar archive from a directory using `tar.c` and then extract its contents to another directory using `tar.x`. It includes setup and cleanup of temporary files.
import { resolve } from 'path';
import { createWriteStream, createReadStream, promises as fsPromises } from 'fs';
import tar from 'tar'; // Using ESM import style for modern projects
const sourceDir = resolve('./files_to_archive');
const archivePath = resolve('./my-archive.tar');
const extractPath = resolve('./extracted_files');
async function setupFiles() {
await fsPromises.mkdir(sourceDir, { recursive: true });
await fsPromises.writeFile(resolve(sourceDir, 'file1.txt'), 'Hello, World 1!');
await fsPromises.writeFile(resolve(sourceDir, 'file2.txt'), 'Hello, World 2!');
console.log('Source directory and files created.');
}
async function createAndExtractTar() {
await setupFiles();
// 1. Create a tar archive
console.log(`Creating tar archive from ${sourceDir} to ${archivePath}`);
const pack = tar.Pack({
cwd: sourceDir, // Set current working directory for packing
gzip: false, // No gzip for simplicity in this example
});
const output = createWriteStream(archivePath);
pack.pipe(output);
// Add entries to the pack stream. 'dot: true' includes hidden files/folders
// 'glob: false' means it expects explicit files/dirs, but `.` works for current dir
// For packing a directory, tar.c is often simpler
await tar.c(
{
gzip: false,
file: archivePath,
cwd: sourceDir,
},
['.'] // Archive the current directory (sourceDir)
);
console.log('Tar archive created successfully.');
// 2. Extract the tar archive
await fsPromises.mkdir(extractPath, { recursive: true });
console.log(`Extracting tar archive ${archivePath} to ${extractPath}`);
await tar.x(
{
file: archivePath,
cwd: extractPath,
}
);
console.log('Tar archive extracted successfully.');
// Verify extracted files
const extractedFiles = await fsPromises.readdir(extractPath);
console.log('Files in extracted directory:', extractedFiles);
// Clean up
await fsPromises.rm(sourceDir, { recursive: true, force: true });
await fsPromises.rm(archivePath, { force: true });
await fsPromises.rm(extractPath, { recursive: true, force: true });
console.log('Cleanup complete.');
}
createAndExtractTar().catch(console.error);
Debug
Known issues
breakingMultiple critical path traversal vulnerabilities have been identified and patched across different major versions, including CVE-2026-23745 (affecting <=7.5.2), CVE-2026-24842, and CVE-2021-32803. These flaws allowed malicious archives to bypass extraction root restrictions, potentially leading to arbitrary file overwrites, symlink poisoning, and unauthorized information disclosure. Always upgrade to the latest patch version as soon as possible.fixUpgrade `node-tar` to version `7.5.3` or later. Regularly audit dependencies using `npm audit` or `yarn audit`. When extracting untrusted archives, consider running processes in sandboxed environments with limited filesystem access and always validate archive entries for suspicious paths, even with the latest version.
affects: <=7.5.2 (for latest critical CVE) and various older versions
gotcha`tar.Pack()` and the low-level stream API generally expect to archive directories or multiple files piped from `fstream` or similar sources. Attempting to pass individual file paths directly to `tar.Pack()` without wrapping them in an appropriate stream (like `fstream.Reader`) or using the higher-level `tar.c` utility will not work as intuitively as expected.fixTo archive a single file or a collection of files/directories, use the convenience methods `tar.c()` (create) for packing or ensure you are using `fstream.Reader` to pipe file data into `tar.Pack()`'s stream. For example, `tar.c({ file: 'archive.tar' }, ['file1.txt', 'dir/']).then(...)`. affects: All versions
gotchaWhen using `tar.Extract()` or `tar.x()` to extract archives, by default, paths within the tarball are relative to the `cwd` option. However, malicious tar archives can include entries with absolute paths or `..` path segments, attempting to write files outside the intended extraction directory. While `node-tar` includes protections, historical vulnerabilities demonstrate that these can be bypassed.fixAlways ensure `node-tar` is updated to the latest secure version. For critical applications, explicitly set `strip: N` (where N is the number of path segments to strip) or implement `onentry` handlers to inspect and potentially reject suspicious `entry.path` values. Run extraction in isolated, least-privilege environments.
affects: All versions, especially older ones
gotchaNode.js modules can be either CommonJS (CJS) or ECMAScript Modules (ESM). `node-tar` is a CommonJS package. While Node.js provides interoperability, directly using named `import { Pack } from 'tar'` in an ESM context might lead to unexpected behavior or `undefined` errors if not handled correctly.fixIn ESM modules, prefer `import tar from 'tar';` and then access methods like `tar.Pack` or destructure `const { Pack, Extract } = tar;`. Ensure your project's `package.json` correctly specifies its `type` field if mixing CJS and ESM, or use `.cjs`/`.mjs` extensions where appropriate. affects: All versions when used in ESM projects.
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'pipe')
Attempting to pipe to `tar.Pack()` or `tar.Extract()` when the streams are not properly initialized or are not receiving valid data.
fixEnsure that `tar.Pack()` or `tar.Extract()` are correctly instantiated and that a readable stream is being piped into the writable tar stream, and that the tar stream is piped to a writable output stream (e.g., `fs.createWriteStream`). Verify that the input data format is compatible with the tar stream's expectations.
Error: EONENT: no such file or directory, stat 'single_file.txt'
Attempting to create a tar archive of a single file using `tar.Pack()` with a `cwd` and a single file path directly, or providing paths that don't exist.
fixThe `tar.Pack()` stream typically expects a directory to be packed or receives a stream of entries (e.g., from `fstream.Reader`). If archiving single files or a list of files/directories, use the higher-level `tar.c` (create) function which directly handles file system paths. Example: `tar.c({ file: 'archive.tar' }, ['path/to/file.txt', 'path/to/directory/'])`. Error: EISDIR: illegal operation on a directory, read
This error can occur if you're trying to read a directory as if it were a file, often when directly piping a directory path into `tar.Pack()` without using `fstream` or `tar.c()` correctly.
fixEnsure that when you supply paths to `tar` for archiving, you are using the correct API. For creating a tar from a directory, `tar.c({ cwd: './my-dir', file: 'output.tar' }, ['.'])` is appropriate. When using `tar.Pack()`, you typically pipe an `fstream.Reader` instance initialized with the directory to it. Audit
Dependencies
fstreamrequiredUsed internally by tar.Pack and tar.Extract for interacting with the filesystem.
minipassrequiredCore stream implementation dependency; bumps to major versions of minipass can introduce subtle behavioral changes.