Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

tar for node

License

NotificationsYou must be signed in to change notification settings

isaacs/node-tar

Fast and full-featured Tar for Node.js

The API is designed to mimic the behavior oftar(1) on unix systems.If you are familiar with how tar works, most of this will hopefully bestraightforward for you. If not, then hopefully this module can teachyou useful unix skills that may come in handy someday :)

Background

A "tar file" or "tarball" is an archive of file system entries(directories, files, links, etc.) The name comes from "tape archive".If you runman tar on almost any Unix command line, you'll learnquite a bit about what it can do, and its history.

Tar has 5 main top-level commands:

  • c Create an archive
  • r Replace entries within an archive
  • u Update entries within an archive (ie, replace if they're newer)
  • t List out the contents of an archive
  • x Extract an archive to disk

The other flags and options modify how this top level function works.

High-Level API

These 5 functions are the high-level API. All of them have asingle-character name (for unix nerds familiar withtar(1)) as wellas a long name (for everyone else).

All the high-level functions take the following arguments, all threeof which are optional and may be omitted.

  1. options - An optional object specifying various options
  2. paths - An array of paths to add or extract
  3. callback - Called when the command is completed, if async. (Ifsync or no file specified, providing a callback throws aTypeError.)

If the command is sync (ie, ifoptions.sync=true), then thecallback is not allowed, since the action will be completed immediately.

If afile argument is specified, and the command is async, then aPromise is returned. In this case, if async, a callback may beprovided which is called when the command is completed.

If afile option is not specified, then a stream is returned. Forcreate, this is a readable stream of the generated archive. Forlist andextract this is a writable stream that an archive shouldbe written into. If a file is not specified, then a callback is notallowed, because you're already getting a stream to work with.

replace andupdate only work on existing archives, and so requireafile argument.

Sync commands without a file argument return a stream that acts on itsinput immediately in the same tick. For readable streams, this meansthat all of the data is immediately available by callingstream.read(). For writable streams, it will be acted upon as soonas it is provided, but this can be at any time.

Warnings and Errors

Tar emits warnings and errors for recoverable and unrecoverable situations,respectively. In many cases, a warning only affects a single entry in anarchive, or is simply informing you that it's modifying an entry to complywith the settings provided.

Unrecoverable warnings will always raise an error (ie, emit'error' onstreaming actions, throw for non-streaming sync actions, reject thereturned Promise for non-streaming async operations, or call a providedcallback with anError as the first argument). Recoverable errors willraise an error only ifstrict: true is set in the options.

Respond to (recoverable) warnings by listening to thewarn event.Handlers receive 3 arguments:

  • code String. One of the error codes below. This may not matchdata.code, which preserves the original error code from fs and zlib.
  • message String. More details about the error.
  • data Metadata about the error. AnError object for errors raised byfs and zlib. All fields are attached to errors raisd by tar. Typicallycontains the following fields, as relevant:
    • tarCode The tar error code.
    • code Either the tar error code, or the error code set by theunderlying system.
    • file The archive file being read or written.
    • cwd Working directory for creation and extraction operations.
    • entry The entry object (if it could be created) forTAR_ENTRY_INFO,TAR_ENTRY_INVALID, andTAR_ENTRY_ERROR warnings.
    • header The header object (if it could be created, and the entry couldnot be created) forTAR_ENTRY_INFO andTAR_ENTRY_INVALID warnings.
    • recoverable Boolean. Iffalse, then the warning will emit anerror, even in non-strict mode.

Error Codes

  • TAR_ENTRY_INFO An informative error indicating that an entry is beingmodified, but otherwise processed normally. For example, removing/ orC:\ from absolute paths ifpreservePaths is not set.

  • TAR_ENTRY_INVALID An indication that a given entry is not a valid tararchive entry, and will be skipped. This occurs when:

    • a checksum fails,
    • alinkpath is missing for a link type, or
    • alinkpath is provided for a non-link type.

    If every entry in a parsed archive raises anTAR_ENTRY_INVALID error,then the archive is presumed to be unrecoverably broken, andTAR_BAD_ARCHIVE will be raised.

  • TAR_ENTRY_ERROR The entry appears to be a valid tar archive entry, butencountered an error which prevented it from being unpacked. This occurswhen:

    • an unrecoverable fs error happens during unpacking,
    • an entry is trying to extract into an excessively deeplocation (by default, limited to 1024 subfolders),
    • an entry has.. in the path andpreservePaths is not set, or
    • an entry is extracting through a symbolic link, whenpreservePaths isnot set.
  • TAR_ENTRY_UNSUPPORTED An indication that a given entry isa valid archive entry, but of a type that is unsupported, and so will beskipped in archive creation or extracting.

  • TAR_ABORT When parsing gzipped-encoded archives, the parser willabort the parse process raise a warning for any zlib errors encountered.Aborts are considered unrecoverable for both parsing and unpacking.

  • TAR_BAD_ARCHIVE The archive file is totally hosed. This can happen fora number of reasons, and always occurs at the end of a parse or extract:

    • An entry body was truncated before seeing the full number of bytes.
    • The archive contained only invalid entries, indicating that it islikely not an archive, or at least, not an archive this library canparse.

    TAR_BAD_ARCHIVE is considered informative for parse operations, butunrecoverable for extraction. Note that, if encountered at the end of anextraction, tar WILL still have extracted as much it could from thearchive, so there may be some garbage files to clean up.

Errors that occur deeper in the system (ie, either the filesystem or zlib)will have their error codes left intact, and atarCode matching one ofthe above will be added to the warning metadata or the raised error object.

Errors generated by tar will have one of the above codes set as theerror.code field as well, but since errors originating in zlib or fs willhave their original codes, it's better to readerror.tarCode if you wishto see how tar is handling the issue.

Examples

The API mimics thetar(1) command line functionality, with aliasesfor more human-readable option and function names. The goal is thatif you know how to usetar(1) in Unix, then you know how to useimport('tar') in JavaScript.

To replicatetar czf my-tarball.tgz files and folders, you'd do:

import{create}from'tar'create({gzip:<true|gzipoptions>,    file: 'my-tarball.tgz'},['some','files','and','folders']).then(_=>{..tarballhasbeencreated..})

To replicatetar cz files and folders > my-tarball.tgz, you'd do:

// if you're familiar with the tar(1) cli flags, this can be niceimport*astarfrom'tar'tar.c({// 'z' is alias for 'gzip' optionz:<true|gzipoptions>},['some','files','and','folders']).pipe(fs.createWriteStream('my-tarball.tgz'))

To replicatetar xf my-tarball.tgz you'd do:

tar.x(// or `tar.extract`{// or `file:`f:'my-tarball.tgz'}).then(_=>{..tarballhasbeendumpedincwd..})

To replicatecat my-tarball.tgz | tar x -C some-dir --strip=1:

fs.createReadStream('my-tarball.tgz').pipe(tar.x({strip:1,C:'some-dir',// alias for cwd:'some-dir', also ok}),)

To replicatetar tf my-tarball.tgz, do this:

tar.t({file:'my-tarball.tgz',onReadEntry:entry=>{..dowhateverwithit..}})

For example, to just get the list of filenames from an archive:

constgetEntryFilenames=asynctarballFilename=>{constfilenames=[]awaittar.t({file:tarballFilename,onReadEntry:entry=>filenames.push(entry.path),})returnfilenames}

To replicatecat my-tarball.tgz | tar t do:

fs.createReadStream('my-tarball.tgz').pipe(tar.t()).on('entry',entry=>{..dowhateverwithit..})

To do anything synchronous, addsync: true to the options. Notethat sync functions don't take a callback and don't return a promise.When the function returns, it's already done. Sync methods without afile argument return a sync stream, which flushes immediately. But,of course, it still won't be done until you.end() it.

constgetEntryFilenamesSync=tarballFilename=>{constfilenames=[]tar.t({file:tarballFilename,onReadEntry:entry=>filenames.push(entry.path),sync:true,})returnfilenames}

To filter entries, addfilter: <function> to the options.Tar-creating methods call the filter withfilter(path, stat).Tar-reading methods (including extraction) call the filter withfilter(path, entry). The filter is called in thethis-context ofthePack orUnpack stream object.

The arguments list totar t andtar x specify a list of filenamesto extract or list, so they're equivalent to a filter that tests ifthe file is in the list.

For those whoaren't fans of tar's single-character command names:

tar.c === tar.createtar.r === tar.replace (appends to archive, file is required)tar.u === tar.update (appends if newer, file is required)tar.x === tar.extracttar.t === tar.list

Keep reading for all the command descriptions and options, as well asthe low-level API that they are built on.

tar.c(options, fileList, callback) [alias: tar.create]

Create a tarball archive.

ThefileList is an array of paths to add to the tarball. Adding adirectory also adds its children recursively.

An entry infileList that starts with an@ symbol is a tar archivewhose entries will be added. To add a file that starts with@,prepend it with./.

The following options are supported:

  • file Write the tarball archive to the specified filename. If thisis specified, then the callback will be fired when the file has beenwritten, and a promise will be returned that resolves when the fileis written. If a filename is not specified, then a Readable Streamwill be returned which will emit the file data. [Alias:f]
  • sync Act synchronously. If this is set, then any provided filewill be fully written after the call totar.c. If this is set,and a file is not provided, then the resulting stream will alreadyhave the data ready toread oremit('data') as soon as yourequest it.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • strict Treat warnings as crash-worthy errors. Default false.
  • cwd The current working directory for creating the archive.Defaults toprocess.cwd(). [Alias:C]
  • prefix A path portion to prefix onto the entries in the archive.
  • gzip Set to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip() [Alias:z]
  • filter A function that gets called with(path, stat) for eachentry being added. Returntrue to add the entry to the archive,orfalse to omit it.
  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths. [Alias:P]
  • mode The mode to set on the created file archive
  • noDirRecurse Do not recursively archive the contents ofdirectories. [Alias:n]
  • follow Set to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]
  • noPax Suppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.[Alias:m,no-mtime]
  • mtime Set to aDate object to force a specificmtime foreverything added to the archive. Overridden bynoMtime.
  • onWriteEntry Called with eachWriteEntry orWriteEntrySync that is created in the course of writing thearchive.

The following options are mostly internal, but can be modified in someadvanced use cases, such as re-using caches between runs.

  • linkCache A Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.
  • statCache A Map object that caches callslstat.
  • readdirCache A Map object that caches calls toreaddir.
  • jobs A number specifying how many concurrent jobs to run.Defaults to 4.
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.

UsingonWriteEntry to alter entries

TheonWriteEntry function, if provided, will get a referenceto eachentry object on its way into the archive.

If any fields on this entry are changed, then these changes willbe reflected in the entry that is written to the archive.

The return value of the function is ignored. All that matters isthe final state of the entry object. This can also be used totrack the files added to an archive, for example.

import*astarfrom'tar'constfilesAdded=[]tar.c({sync:true,file:'lowercase-executable.tar',onWriteEntry(entry){// initially, it's uppercase and 0o644console.log('adding',entry.path,entry.stat.mode.toString(8))// make all the paths lowercaseentry.path=entry.path.toLowerCase()// make the entry executableentry.stat.mode=0o755// in the archive, it's lowercase and 0o755filesAdded.push([entry.path,entry.stat.mode.toString(8)])},},['./bin'],)console.log('added',filesAdded)

Then, if the./bin directory containedSOME-BIN, it wouldshow up in the archive as:

$ node create-lowercase-executable.jsadding ./bin/SOME-BIN 644added [[ './bin/some-bin', '755' ]]$ tar cvf lowercase-executable.tar-rwxr-xr-x  0 isaacs 20      47731 Aug 14 08:56 ./bin/some-bin

with a lowercase name and a mode of0o755.

tar.x(options, fileList, callback) [alias: tar.extract]

Extract a tarball archive.

ThefileList is an array of paths to extract from the tarball. Ifno paths are provided, then all the entries are extracted.

If the archive is gzipped, then tar will detect this and unzip it.

Note that all directories that are created will be forced to bewritable, readable, and listable by their owner, to avoid cases wherea directory prevents extraction of child entries by virtue of itsmode.

Most extraction errors will cause awarn event to be emitted. Ifthecwd is missing, or not a directory, then the extraction willfail completely.

The following options are supported:

  • cwd Extract files relative to the specified directory. Defaultstoprocess.cwd(). If provided, this must exist and must be adirectory. [Alias:C]
  • file The archive file to extract. If not specified, then aWritable stream is returned where the archive data should bewritten. [Alias:f]
  • sync Create files and directories synchronously.
  • strict Treat warnings as crash-worthy errors. Default false.
  • filter A function that gets called with(path, entry) for eachentry being unpacked. Returntrue to unpack the entry from thearchive, orfalse to skip it.
  • newer Set to true to keep the existing file on disk if it's newerthan the file in the archive. [Alias:keep-newer,keep-newer-files]
  • keep Do not overwrite existing files. In particular, if a fileappears more than once in an archive, later copies will notoverwrite earlier copies. [Alias:k,keep-existing]
  • preservePaths Allow absolute paths, paths containing.., andextracting through symbolic links. By default,/ is stripped fromabsolute paths,.. paths are not extracted, and any file whoselocation would be modified by a symbolic link is not extracted.[Alias:P]
  • unlink Unlink files before creating them. Without this option,tar overwrites existing files, which preserves existing hardlinks.With this option, existing hardlinks will be broken, as will anysymlink that would affect the location of an extracted file. [Alias:U]
  • strip Remove the specified number of leading path elements.Pathnames with fewer elements will be silently skipped. Note thatthe pathname is edited after applying the filter, but beforesecurity checks. [Alias:strip-components,stripComponents]
  • preserveOwner If true, tar will set theuid andgid ofextracted entries to theuid andgid fields in the archive.This defaults to true when run as root, and false otherwise. Iffalse, then files and directories will be set with the owner andgroup of the user running the process. This is similar to-p intar(1), but ACLs and other system-specific data is never unpackedin this implementation, and modes are set by default already.[Alias:p]
  • uid Set to a number to force ownership of all extracted files andfolders, and all implicitly created directories, to be owned by thespecified user id, regardless of theuid field in the archive.Cannot be used along withpreserveOwner. Requires also setting agid option.
  • gid Set to a number to force ownership of all extracted files andfolders, and all implicitly created directories, to be owned by thespecified group id, regardless of thegid field in the archive.Cannot be used along withpreserveOwner. Requires also setting auid option.
  • noMtime Set to true to omit writingmtime value for extractedentries. [Alias:m,no-mtime]
  • transform Provide a function that takes anentry object, andreturns a stream, or any falsey value. If a stream is provided,then that stream's data will be written instead of the contents ofthe archive entry. If a falsey value is provided, then the entry iswritten to disk as normal. (To exclude items from extraction, usethefilter option described above.)
  • onReadEntry A function that gets called with(entry) for each entrythat passes the filter.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • chmod Set to true to callfs.chmod() to ensure that theextracted file matches the entry mode. This may necessitate acall to the deprecated and thread-unsafeprocess.umask()method to determine the default umask value, unless aprocessUmask options is also provided. Otherwise tar willextract with whatever mode is provided, and let the processumask apply normally.
  • processUmask Set to an explicit numeric value to avoidcallingprocess.umask() whenchmod: true is set.
  • maxDepth The maximum depth of subfolders to extract into. Thisdefaults to 1024. Anything deeper than the limit will raise awarning and skip the entry. Set toInfinity to remove thelimitation.

The following options are mostly internal, but can be modified in someadvanced use cases, such as re-using caches between runs.

  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.
  • umask Filter the modes of entries likeprocess.umask().
  • dmode Default mode for directories
  • fmode Default mode for files
  • maxMetaEntrySize The maximum size of meta entries that issupported. Defaults to 1 MB.

Note that using an asynchronous stream type with thetransformoption will cause undefined behavior in sync extractions.MiniPass-based streams are designed for thisuse case.

tar.t(options, fileList, callback) [alias: tar.list]

List the contents of a tarball archive.

ThefileList is an array of paths to list from the tarball. Ifno paths are provided, then all the entries are listed.

If the archive is gzipped, then tar will detect this and unzip it.

If thefile option isnot provided, then returns an event emitter thatemitsentry events withtar.ReadEntry objects. However, they don'temit'data' or'end' events. (If you want to get actual readableentries, use thetar.Parser class instead.)

If afile optionis provided, then the return value will be a promisethat resolves when the file has been fully traversed in async mode, orundefined ifsync: true is set. Thus, youmust specify anonReadEntrymethod in order to do anything useful with the data it parses.

The following options are supported:

  • file The archive file to list. If not specified, then aWritable stream is returned where the archive data should bewritten. [Alias:f]
  • sync Read the specified file synchronously. (This has no effectwhen a file option isn't specified, because entries are emitted asfast as they are parsed from the stream anyway.)
  • strict Treat warnings as crash-worthy errors. Default false.
  • filter A function that gets called with(path, entry) for eachentry being listed. Returntrue to emit the entry from thearchive, orfalse to skip it.
  • onReadEntry A function that gets called with(entry) for each entrythat passes the filter. This is important for whenfile is set,because there is no other way to do anything useful with this method.
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.
  • noResume By default,entry streams are resumed immediately afterthe call toonReadEntry. SetnoResume: true to suppress thisbehavior. Note that by opting into this, the stream will nevercomplete until the entry data is consumed.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")

tar.u(options, fileList, callback) [alias: tar.update]

Add files to an archive if they are newer than the entry already inthe tarball archive.

ThefileList is an array of paths to add to the tarball. Adding adirectory also adds its children recursively.

An entry infileList that starts with an@ symbol is a tar archivewhose entries will be added. To add a file that starts with@,prepend it with./.

The following options are supported:

  • file Required. Write the tarball archive to the specifiedfilename. [Alias:f]
  • sync Act synchronously. If this is set, then any provided filewill be fully written after the call totar.c.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • strict Treat warnings as crash-worthy errors. Default false.
  • cwd The current working directory for adding entries to thearchive. Defaults toprocess.cwd(). [Alias:C]
  • prefix A path portion to prefix onto the entries in the archive.
  • gzip Set to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip() [Alias:z]
  • filter A function that gets called with(path, stat) for eachentry being added. Returntrue to add the entry to the archive,orfalse to omit it.
  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths. [Alias:P]
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.
  • noDirRecurse Do not recursively archive the contents ofdirectories. [Alias:n]
  • follow Set to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]
  • noPax Suppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.[Alias:m,no-mtime]
  • mtime Set to aDate object to force a specificmtime foreverything added to the archive. Overridden bynoMtime.
  • onWriteEntry Called with eachWriteEntry orWriteEntrySync that is created in the course of writing thearchive.

tar.r(options, fileList, callback) [alias: tar.replace]

Add files to an existing archive. Because later entries overrideearlier entries, this effectively replaces any existing entries.

ThefileList is an array of paths to add to the tarball. Adding adirectory also adds its children recursively.

An entry infileList that starts with an@ symbol is a tar archivewhose entries will be added. To add a file that starts with@,prepend it with./.

The following options are supported:

  • file Required. Write the tarball archive to the specifiedfilename. [Alias:f]
  • sync Act synchronously. If this is set, then any provided filewill be fully written after the call totar.c.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • strict Treat warnings as crash-worthy errors. Default false.
  • cwd The current working directory for adding entries to thearchive. Defaults toprocess.cwd(). [Alias:C]
  • prefix A path portion to prefix onto the entries in the archive.
  • gzip Set to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip() [Alias:z]
  • filter A function that gets called with(path, stat) for eachentry being added. Returntrue to add the entry to the archive,orfalse to omit it.
  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths. [Alias:P]
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.
  • noDirRecurse Do not recursively archive the contents ofdirectories. [Alias:n]
  • follow Set to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]
  • noPax Suppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.[Alias:m,no-mtime]
  • mtime Set to aDate object to force a specificmtime foreverything added to the archive. Overridden bynoMtime.
  • onWriteEntry Called with eachWriteEntry orWriteEntrySync that is created in the course of writing thearchive.

Low-Level API

class Pack

A readable tar stream.

Has all the standard readable stream interface stuff.'data' and'end' events,read() method,pause() andresume(), etc.

constructor(options)

The following options are supported:

  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • strict Treat warnings as crash-worthy errors. Default false.
  • cwd The current working directory for creating the archive.Defaults toprocess.cwd().
  • prefix A path portion to prefix onto the entries in the archive.
  • gzip Set to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip()
  • filter A function that gets called with(path, stat) for eachentry being added. Returntrue to add the entry to the archive,orfalse to omit it.
  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths.
  • linkCache A Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.
  • statCache A Map object that caches callslstat.
  • readdirCache A Map object that caches calls toreaddir.
  • jobs A number specifying how many concurrent jobs to run.Defaults to 4.
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 16 MB.
  • noDirRecurse Do not recursively archive the contents ofdirectories.
  • follow Set to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such.
  • noPax Suppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.
  • mtime Set to aDate object to force a specificmtime foreverything added to the archive. Overridden bynoMtime.
  • onWriteEntry Called with eachWriteEntry orWriteEntrySync that is created in the course of writing thearchive.

add(path)

Adds an entry to the archive. Returns the Pack stream.

write(path)

Adds an entry to the archive. Returns true if flushed.

end()

Finishes the archive.

class PackSync

Synchronous version ofPack.

class Unpack

A writable stream that unpacks a tar archive onto the file system.

All the normal writable stream stuff is supported.write() andend() methods,'drain' events, etc.

Note that all directories that are created will be forced to bewritable, readable, and listable by their owner, to avoid cases wherea directory prevents extraction of child entries by virtue of itsmode.

'close' is emitted when it's done writing stuff to the file system.

Most unpack errors will cause awarn event to be emitted. If thecwd is missing, or not a directory, then an error will be emitted.

constructor(options)

  • cwd Extract files relative to the specified directory. Defaultstoprocess.cwd(). If provided, this must exist and must be adirectory.
  • filter A function that gets called with(path, entry) for eachentry being unpacked. Returntrue to unpack the entry from thearchive, orfalse to skip it.
  • newer Set to true to keep the existing file on disk if it's newerthan the file in the archive.
  • keep Do not overwrite existing files. In particular, if a fileappears more than once in an archive, later copies will notoverwrite earlier copies.
  • preservePaths Allow absolute paths, paths containing.., andextracting through symbolic links. By default,/ is stripped fromabsolute paths,.. paths are not extracted, and any file whoselocation would be modified by a symbolic link is not extracted.
  • unlink Unlink files before creating them. Without this option,tar overwrites existing files, which preserves existing hardlinks.With this option, existing hardlinks will be broken, as will anysymlink that would affect the location of an extracted file.
  • strip Remove the specified number of leading path elements.Pathnames with fewer elements will be silently skipped. Note thatthe pathname is edited after applying the filter, but beforesecurity checks.
  • umask Filter the modes of entries likeprocess.umask().
  • dmode Default mode for directories
  • fmode Default mode for files
  • maxMetaEntrySize The maximum size of meta entries that issupported. Defaults to 1 MB.
  • preserveOwner If true, tar will set theuid andgid ofextracted entries to theuid andgid fields in the archive.This defaults to true when run as root, and false otherwise. Iffalse, then files and directories will be set with the owner andgroup of the user running the process. This is similar to-p intar(1), but ACLs and other system-specific data is never unpackedin this implementation, and modes are set by default already.
  • win32 True if on a windows platform. Causes behavior wherefilenames containing<|>? chars are converted towindows-compatible values while being unpacked.
  • uid Set to a number to force ownership of all extracted files andfolders, and all implicitly created directories, to be owned by thespecified user id, regardless of theuid field in the archive.Cannot be used along withpreserveOwner. Requires also setting agid option.
  • gid Set to a number to force ownership of all extracted files andfolders, and all implicitly created directories, to be owned by thespecified group id, regardless of thegid field in the archive.Cannot be used along withpreserveOwner. Requires also setting auid option.
  • noMtime Set to true to omit writingmtime value for extractedentries.
  • transform Provide a function that takes anentry object, andreturns a stream, or any falsey value. If a stream is provided,then that stream's data will be written instead of the contents ofthe archive entry. If a falsey value is provided, then the entry iswritten to disk as normal. (To exclude items from extraction, usethefilter option described above.)
  • strict Treat warnings as crash-worthy errors. Default false.
  • onReadEntry A function that gets called with(entry) for each entrythat passes the filter.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • chmod Set to true to callfs.chmod() to ensure that theextracted file matches the entry mode. This may necessitate acall to the deprecated and thread-unsafeprocess.umask()method to determine the default umask value, unless aprocessUmask options is also provided. Otherwise tar willextract with whatever mode is provided, and let the processumask apply normally.
  • processUmask Set to an explicit numeric value to avoidcallingprocess.umask() whenchmod: true is set.
  • maxDepth The maximum depth of subfolders to extract into. Thisdefaults to 1024. Anything deeper than the limit will raise awarning and skip the entry. Set toInfinity to remove thelimitation.

class UnpackSync

Synchronous version ofUnpack.

Note that using an asynchronous stream type with thetransformoption will cause undefined behavior in sync unpack streams.MiniPass-based streams are designed for thisuse case.

class tar.Parser

A writable stream that parses a tar archive stream. All the standardwritable stream stuff is supported.

If the archive is gzipped, then tar will detect this and unzip it.

Emits'entry' events withtar.ReadEntry objects, which arethemselves readable streams that you can pipe wherever.

Eachentry will not emit until the one before it is flushed through,so make sure to either consume the data (withon('data', ...) or.pipe(...)) or throw it away with.resume() to keep the streamflowing.

constructor(options)

Returns an event emitter that emitsentry events withtar.ReadEntry objects.

The following options are supported:

  • strict Treat warnings as crash-worthy errors. Default false.
  • filter A function that gets called with(path, entry) for eachentry being listed. Returntrue to emit the entry from thearchive, orfalse to skip it.
  • onReadEntry A function that gets called with(entry) for each entrythat passes the filter.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")

abort(error)

Stop all parsing activities. This is called when there are zliberrors. It also emits an unrecoverable warning with the error provided.

class tar.ReadEntry extendsMiniPass

A representation of an entry that is being read out of a tar archive.

It has the following fields:

  • extended The extended metadata object provided to the constructor.
  • globalExtended The global extended metadata object provided to theconstructor.
  • remain The number of bytes remaining to be written into thestream.
  • blockRemain The number of 512-byte blocks remaining to be writteninto the stream.
  • ignore Whether this entry should be ignored.
  • meta True if this represents metadata about the next entry, falseif it represents a filesystem object.
  • All the fields from the header, extended header, and global extendedheader are added to the ReadEntry object. So it haspath,type,size,mode, and so on.

constructor(header, extended, globalExtended)

Create a new ReadEntry object with the specified header, extendedheader, and global extended header values.

class tar.WriteEntry extendsMiniPass

A representation of an entry that is being written from the filesystem into a tar archive.

Emits data for the Header, and for the Pax Extended Header if one isrequired, as well as any body data.

Creating a WriteEntry for a directory does not also createWriteEntry objects for all of the directory contents.

It has the following fields:

  • path The path field that will be written to the archive. Bydefault, this is also the path from the cwd to the file systemobject.
  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • myuid If supported, the uid of the user running the currentprocess.
  • myuser Theenv.USER string if set, or''. Set as the entryuname field if the file'suid matchesthis.myuid.
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 1 MB.
  • linkCache A Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.
  • statCache A Map object that caches callslstat.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths.
  • cwd The current working directory for creating the archive.Defaults toprocess.cwd().
  • absolute The absolute path to the entry on the filesystem. Bydefault, this ispath.resolve(this.cwd, this.path), but it can beoverridden explicitly.
  • strict Treat warnings as crash-worthy errors. Default false.
  • win32 True if on a windows platform. Causes behavior where pathsreplace\ with/ and filenames containing the windows-compatibleforms of<|>?: characters are converted to actual<|>?: charactersin the archive.
  • noPax Suppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.

constructor(path, options)

path is the path of the entry as it is written in the archive.

The following options are supported:

  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • maxReadSize The maximum buffer size forfs.read() operations.Defaults to 1 MB.
  • linkCache A Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.
  • statCache A Map object that caches callslstat.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths.
  • cwd The current working directory for creating the archive.Defaults toprocess.cwd().
  • absolute The absolute path to the entry on the filesystem. Bydefault, this ispath.resolve(this.cwd, this.path), but it can beoverridden explicitly.
  • strict Treat warnings as crash-worthy errors. Default false.
  • win32 True if on a windows platform. Causes behavior where pathsreplace\ with/.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.
  • umask Set to restrict the modes on the entries in the archive,somewhat like how umask works on file creation. Defaults toprocess.umask() on unix systems, or0o22 on Windows.

warn(message, data)

If strict, emit an error with the provided message.

Otherwise, emit a'warn' event with the provided message and data.

class tar.WriteEntry.Sync

Synchronous version of tar.WriteEntry

class tar.WriteEntry.Tar

A version of tar.WriteEntry that gets its data from a tar.ReadEntryinstead of from the filesystem.

constructor(readEntry, options)

readEntry is the entry being read out of another archive.

The following options are supported:

  • portable Omit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtime is still included, because this is necessary for othertime-based operations. Additionally,mode is set to a "reasonabledefault" for most unix systems, based on aumask value of0o22.
  • preservePaths Allow absolute paths. By default,/ is strippedfrom absolute paths.
  • strict Treat warnings as crash-worthy errors. Default false.
  • onwarn A function that will get called with(code, message, data) forany warnings encountered. (See "Warnings and Errors")
  • noMtime Set to true to omit writingmtime values for entries.Note that this prevents using other mtime-based features liketar.update or thekeepNewer option with the resulting tar archive.

class tar.Header

A class for reading and writing header blocks.

It has the following fields:

  • nullBlock True if decoding a block which is entirely composed of0x00 null bytes. (Useful because tar files are terminated byat least 2 null blocks.)
  • cksumValid True if the checksum in the header is valid, falseotherwise.
  • needPax True if the values, as encoded, will require a Paxextended header.
  • path The path of the entry.
  • mode The 4 lowest-order octal digits of the file mode. That is,read/write/execute permissions for world, group, and owner, and thesetuid, setgid, and sticky bits.
  • uid Numeric user id of the file owner
  • gid Numeric group id of the file owner
  • size Size of the file in bytes
  • mtime Modified time of the file
  • cksum The checksum of the header. This is generated by adding allthe bytes of the header block, treating the checksum field itself asall ascii space characters (that is,0x20).
  • type The human-readable name of the type of entry this represents,or the alphanumeric key if unknown.
  • typeKey The alphanumeric key for the type of entry this headerrepresents.
  • linkpath The target of Link and SymbolicLink entries.
  • uname Human-readable user name of the file owner
  • gname Human-readable group name of the file owner
  • devmaj The major portion of the device number. Always0 forfiles, directories, and links.
  • devmin The minor portion of the device number. Always0 forfiles, directories, and links.
  • atime File access time.
  • ctime File change time.

constructor(data, [offset=0])

data is optional. It is either a Buffer that should be interpretedas a tar Header starting at the specified offset and continuing for512 bytes, or a data object of keys and values to set on the headerobject, and eventually encode as a tar Header.

decode(block, offset)

Decode the provided buffer starting at the specified offset.

Buffer length must be greater than 512 bytes.

set(data)

Set the fields in the data object.

encode(buffer, offset)

Encode the header fields into the buffer at the specified offset.

Returnsthis.needPax to indicate whether a Pax Extended Header isrequired to properly encode the specified data.

class tar.Pax

An object representing a set of key-value pairs in an Pax extendedheader entry.

It has the following fields. Where the same name is used, they havethe same semantics as the tar.Header field of the same name.

  • global True if this represents a global extended header, or falseif it is for a single entry.
  • atime
  • charset
  • comment
  • ctime
  • gid
  • gname
  • linkpath
  • mtime
  • path
  • size
  • uid
  • uname
  • dev
  • ino
  • nlink

constructor(object, global)

Set the fields set in the object.global is a boolean that defaultsto false.

encode()

Return a Buffer containing the header and body for the Pax extendedheader entry, ornull if there is nothing to encode.

encodeBody()

Return a string representing the body of the pax extended headerentry.

encodeField(fieldName)

Return a string representing the key/value encoding for the specifiedfieldName, or'' if the field is unset.

tar.Pax.parse(string, extended, global)

Return a new Pax object created by parsing the contents of the stringprovided.

If theextended object is set, then also add the fields from thatobject. (This is necessary because multiple metadata entries canoccur in sequence.)

tar.types

A translation table for thetype field in tar headers.

tar.types.name.get(code)

Get the human-readable name for a given alphanumeric code.

tar.types.code.get(name)

Get the alphanumeric code for a given human-readable name.

About

tar for node

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp