{"id":14102,"library":"tarr","title":"tar for Node.js","description":"tar is a Node.js library designed for creating, extracting, and parsing tar archives. It leverages Node.js streams for efficient processing, allowing it to handle archive data without extensive memory usage. The package is currently at version 6.1.13, with a release cadence that addresses bugs and updates internal dependencies. A key differentiator is its low-level, stream-centric API, which integrates seamlessly with other Node.js stream utilities like `fstream` for direct filesystem interaction. This makes `tar` particularly well-suited for high-throughput archiving operations often found in build tools, deployment scripts, and server-side applications requiring robust tarball manipulation.","status":"active","version":"1.1.0","language":"javascript","source_language":"en","source_url":"git://github.com/isaacs/node-tar","tags":["javascript"],"install":[{"cmd":"npm install tarr","lang":"bash","label":"npm"},{"cmd":"yarn add tarr","lang":"bash","label":"yarn"},{"cmd":"pnpm add tarr","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used internally by tar.Pack and tar.Extract for interacting with the filesystem.","package":"fstream","optional":false},{"reason":"Core stream implementation dependency; bumps to major versions of minipass can introduce subtle behavioral changes.","package":"minipass","optional":false}],"imports":[{"note":"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.","wrong":"const tar = require('tar');","symbol":"tar","correct":"import tar from 'tar';\n// Or for direct access to methods:\n// import { Pack, Extract, Parse } from 'tar'; // Less common if type is 'commonjs'\n// const { Pack, Extract, Parse } = tar;"},{"note":"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.","wrong":"import { Pack } from 'tar';\nconst packStream = Pack();","symbol":"Pack","correct":"const tar = require('tar');\nconst packStream = tar.Pack();"},{"note":"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.","wrong":"import tar from 'tar';\nconst extractStream = tar.extract({ path: './output' });","symbol":"Extract","correct":"const tar = require('tar');\nconst extractStream = tar.Extract({ path: './output' });"}],"quickstart":{"code":"import { resolve } from 'path';\nimport { createWriteStream, createReadStream, promises as fsPromises } from 'fs';\nimport tar from 'tar'; // Using ESM import style for modern projects\n\nconst sourceDir = resolve('./files_to_archive');\nconst archivePath = resolve('./my-archive.tar');\nconst extractPath = resolve('./extracted_files');\n\nasync function setupFiles() {\n  await fsPromises.mkdir(sourceDir, { recursive: true });\n  await fsPromises.writeFile(resolve(sourceDir, 'file1.txt'), 'Hello, World 1!');\n  await fsPromises.writeFile(resolve(sourceDir, 'file2.txt'), 'Hello, World 2!');\n  console.log('Source directory and files created.');\n}\n\nasync function createAndExtractTar() {\n  await setupFiles();\n\n  // 1. Create a tar archive\n  console.log(`Creating tar archive from ${sourceDir} to ${archivePath}`);\n  const pack = tar.Pack({\n    cwd: sourceDir, // Set current working directory for packing\n    gzip: false,    // No gzip for simplicity in this example\n  });\n  const output = createWriteStream(archivePath);\n  pack.pipe(output);\n\n  // Add entries to the pack stream. 'dot: true' includes hidden files/folders\n  // 'glob: false' means it expects explicit files/dirs, but `.` works for current dir\n  // For packing a directory, tar.c is often simpler\n  await tar.c(\n    {\n      gzip: false,\n      file: archivePath,\n      cwd: sourceDir,\n    },\n    ['.'] // Archive the current directory (sourceDir)\n  );\n  console.log('Tar archive created successfully.');\n\n  // 2. Extract the tar archive\n  await fsPromises.mkdir(extractPath, { recursive: true });\n  console.log(`Extracting tar archive ${archivePath} to ${extractPath}`);\n  await tar.x(\n    {\n      file: archivePath,\n      cwd: extractPath,\n    }\n  );\n  console.log('Tar archive extracted successfully.');\n\n  // Verify extracted files\n  const extractedFiles = await fsPromises.readdir(extractPath);\n  console.log('Files in extracted directory:', extractedFiles);\n\n  // Clean up\n  await fsPromises.rm(sourceDir, { recursive: true, force: true });\n  await fsPromises.rm(archivePath, { force: true });\n  await fsPromises.rm(extractPath, { recursive: true, force: true });\n  console.log('Cleanup complete.');\n}\n\ncreateAndExtractTar().catch(console.error);\n","lang":"javascript","description":"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."},"warnings":[{"fix":"Upgrade `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.","message":"Multiple 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.","severity":"breaking","affected_versions":"<=7.5.2 (for latest critical CVE) and various older versions"},{"fix":"To 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(...)`.","message":"`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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always 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.","message":"When 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.","severity":"gotcha","affected_versions":"All versions, especially older ones"},{"fix":"In 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.","message":"Node.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.","severity":"gotcha","affected_versions":"All versions when used in ESM projects."}],"env_vars":null,"search_vec":"'6.1.13':40 'address':46 'allow':24 'api':63 'applic':102 'archiv':16,28,89 'bug':47 'build':94 'cadenc':44 'centric':62 'creat':11 'current':37 'data':29 'depend':51 'deploy':96 'design':9 'differenti':54 'direct':75 'effici':22 'extens':31 'extract':12 'filesystem':76 'found':92 'fstream':73 'handl':27 'high':87 'high-throughput':86 'integr':65 'interact':77 'intern':50 'javascript':107 'key':53 'level':59 'leverag':18 'librari':8 'like':72 'low':58 'low-level':57 'make':79 'manipul':106 'memori':32 'node.js':3,7,19,69 'often':91 'oper':90 'packag':35 'pars':14 'particular':81 'process':23 'releas':43 'requir':103 'robust':104 'script':97 'seamless':66 'server':100 'server-sid':99 'side':101 'stream':20,61,70 'stream-centr':60 'suit':84 'tar':1,4,15,80 'tarbal':105 'throughput':88 'tool':95 'updat':49 'usag':33 'util':71 'version':39 'well':83 'well-suit':82 'without':30","created_at":"2026-04-20T01:57:56.382890+00:00","updated_at":"2026-04-20T01:57:56.382890+00:00","problems":[{"fix":"Ensure 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.","cause":"Attempting to pipe to `tar.Pack()` or `tar.Extract()` when the streams are not properly initialized or are not receiving valid data.","error":"TypeError: Cannot read properties of undefined (reading 'pipe')"},{"fix":"The `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/'])`.","cause":"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.","error":"Error: EONENT: no such file or directory, stat 'single_file.txt'"},{"fix":"Ensure 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.","cause":"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.","error":"Error: EISDIR: illegal operation on a directory, read"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.1.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/isaacs/node-tar","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/tarr","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}