Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork198
isaacs/node-tar
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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 :)
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:
cCreate an archiverReplace entries within an archiveuUpdate entries within an archive (ie, replace if they're newer)tList out the contents of an archivexExtract an archive to disk
The other flags and options modify how this top level function works.
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.
options- An optional object specifying various optionspaths- An array of paths to add or extractcallback- 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.
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:
codeString. One of the error codes below. This may not matchdata.code, which preserves the original error code from fs and zlib.messageString. More details about the error.dataMetadata about the error. AnErrorobject for errors raised byfs and zlib. All fields are attached to errors raisd by tar. Typicallycontains the following fields, as relevant:tarCodeThe tar error code.codeEither the tar error code, or the error code set by theunderlying system.fileThe archive file being read or written.cwdWorking directory for creation and extraction operations.entryThe entry object (if it could be created) forTAR_ENTRY_INFO,TAR_ENTRY_INVALID, andTAR_ENTRY_ERRORwarnings.headerThe header object (if it could be created, and the entry couldnot be created) forTAR_ENTRY_INFOandTAR_ENTRY_INVALIDwarnings.recoverableBoolean. Iffalse, then the warning will emit anerror, even in non-strict mode.
TAR_ENTRY_INFOAn informative error indicating that an entry is beingmodified, but otherwise processed normally. For example, removing/orC:\from absolute paths ifpreservePathsis not set.TAR_ENTRY_INVALIDAn indication that a given entry is not a valid tararchive entry, and will be skipped. This occurs when:- a checksum fails,
- a
linkpathis missing for a link type, or - a
linkpathis provided for a non-link type.
If every entry in a parsed archive raises an
TAR_ENTRY_INVALIDerror,then the archive is presumed to be unrecoverably broken, andTAR_BAD_ARCHIVEwill be raised.TAR_ENTRY_ERRORThe 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 andpreservePathsis not set, or - an entry is extracting through a symbolic link, when
preservePathsisnot set.
TAR_ENTRY_UNSUPPORTEDAn 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_ABORTWhen 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_ARCHIVEThe 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_ARCHIVEis 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.
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.listKeep reading for all the command descriptions and options, as well asthe low-level API that they are built on.
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:
fileWrite 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]syncAct 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 toreadoremit('data')as soon as yourequest it.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")strictTreat warnings as crash-worthy errors. Default false.cwdThe current working directory for creating the archive.Defaults toprocess.cwd(). [Alias:C]prefixA path portion to prefix onto the entries in the archive.gzipSet to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip()[Alias:z]filterA function that gets called with(path, stat)for eachentry being added. Returntrueto add the entry to the archive,orfalseto omit it.portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths. [Alias:P]modeThe mode to set on the created file archivenoDirRecurseDo not recursively archive the contents ofdirectories. [Alias:n]followSet to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]noPaxSuppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.[Alias:m,no-mtime]mtimeSet to aDateobject to force a specificmtimeforeverything added to the archive. Overridden bynoMtime.onWriteEntryCalled with eachWriteEntryorWriteEntrySyncthat 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.
linkCacheA Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.statCacheA Map object that caches callslstat.readdirCacheA Map object that caches calls toreaddir.jobsA number specifying how many concurrent jobs to run.Defaults to 4.maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.
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-binwith a lowercase name and a mode of0o755.
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:
cwdExtract files relative to the specified directory. Defaultstoprocess.cwd(). If provided, this must exist and must be adirectory. [Alias:C]fileThe archive file to extract. If not specified, then aWritable stream is returned where the archive data should bewritten. [Alias:f]syncCreate files and directories synchronously.strictTreat warnings as crash-worthy errors. Default false.filterA function that gets called with(path, entry)for eachentry being unpacked. Returntrueto unpack the entry from thearchive, orfalseto skip it.newerSet to true to keep the existing file on disk if it's newerthan the file in the archive. [Alias:keep-newer,keep-newer-files]keepDo 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]preservePathsAllow 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]unlinkUnlink 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]stripRemove 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]preserveOwnerIf true, tar will set theuidandgidofextracted entries to theuidandgidfields 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-pintar(1), but ACLs and other system-specific data is never unpackedin this implementation, and modes are set by default already.[Alias:p]uidSet 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 theuidfield in the archive.Cannot be used along withpreserveOwner. Requires also setting agidoption.gidSet 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 thegidfield in the archive.Cannot be used along withpreserveOwner. Requires also setting auidoption.noMtimeSet to true to omit writingmtimevalue for extractedentries. [Alias:m,no-mtime]transformProvide a function that takes anentryobject, 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, usethefilteroption described above.)onReadEntryA function that gets called with(entry)for each entrythat passes the filter.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")chmodSet 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 aprocessUmaskoptions is also provided. Otherwise tar willextract with whatever mode is provided, and let the processumaskapply normally.processUmaskSet to an explicit numeric value to avoidcallingprocess.umask()whenchmod: trueis set.maxDepthThe maximum depth of subfolders to extract into. Thisdefaults to 1024. Anything deeper than the limit will raise awarning and skip the entry. Set toInfinityto remove thelimitation.
The following options are mostly internal, but can be modified in someadvanced use cases, such as re-using caches between runs.
maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.umaskFilter the modes of entries likeprocess.umask().dmodeDefault mode for directoriesfmodeDefault mode for filesmaxMetaEntrySizeThe 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.
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:
fileThe archive file to list. If not specified, then aWritable stream is returned where the archive data should bewritten. [Alias:f]syncRead 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.)strictTreat warnings as crash-worthy errors. Default false.filterA function that gets called with(path, entry)for eachentry being listed. Returntrueto emit the entry from thearchive, orfalseto skip it.onReadEntryA function that gets called with(entry)for each entrythat passes the filter. This is important for whenfileis set,because there is no other way to do anything useful with this method.maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.noResumeBy default,entrystreams are resumed immediately afterthe call toonReadEntry. SetnoResume: trueto suppress thisbehavior. Note that by opting into this, the stream will nevercomplete until the entry data is consumed.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")
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:
fileRequired. Write the tarball archive to the specifiedfilename. [Alias:f]syncAct synchronously. If this is set, then any provided filewill be fully written after the call totar.c.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")strictTreat warnings as crash-worthy errors. Default false.cwdThe current working directory for adding entries to thearchive. Defaults toprocess.cwd(). [Alias:C]prefixA path portion to prefix onto the entries in the archive.gzipSet to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip()[Alias:z]filterA function that gets called with(path, stat)for eachentry being added. Returntrueto add the entry to the archive,orfalseto omit it.portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths. [Alias:P]maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.noDirRecurseDo not recursively archive the contents ofdirectories. [Alias:n]followSet to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]noPaxSuppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.[Alias:m,no-mtime]mtimeSet to aDateobject to force a specificmtimeforeverything added to the archive. Overridden bynoMtime.onWriteEntryCalled with eachWriteEntryorWriteEntrySyncthat is created in the course of writing thearchive.
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:
fileRequired. Write the tarball archive to the specifiedfilename. [Alias:f]syncAct synchronously. If this is set, then any provided filewill be fully written after the call totar.c.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")strictTreat warnings as crash-worthy errors. Default false.cwdThe current working directory for adding entries to thearchive. Defaults toprocess.cwd(). [Alias:C]prefixA path portion to prefix onto the entries in the archive.gzipSet to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip()[Alias:z]filterA function that gets called with(path, stat)for eachentry being added. Returntrueto add the entry to the archive,orfalseto omit it.portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths. [Alias:P]maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.noDirRecurseDo not recursively archive the contents ofdirectories. [Alias:n]followSet to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such. [Alias:L,h]noPaxSuppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.[Alias:m,no-mtime]mtimeSet to aDateobject to force a specificmtimeforeverything added to the archive. Overridden bynoMtime.onWriteEntryCalled with eachWriteEntryorWriteEntrySyncthat is created in the course of writing thearchive.
A readable tar stream.
Has all the standard readable stream interface stuff.'data' and'end' events,read() method,pause() andresume(), etc.
The following options are supported:
onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")strictTreat warnings as crash-worthy errors. Default false.cwdThe current working directory for creating the archive.Defaults toprocess.cwd().prefixA path portion to prefix onto the entries in the archive.gzipSet to any truthy value to create a gzipped archive, or anobject with settings forzlib.Gzip()filterA function that gets called with(path, stat)for eachentry being added. Returntrueto add the entry to the archive,orfalseto omit it.portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths.linkCacheA Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.statCacheA Map object that caches callslstat.readdirCacheA Map object that caches calls toreaddir.jobsA number specifying how many concurrent jobs to run.Defaults to 4.maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 16 MB.noDirRecurseDo not recursively archive the contents ofdirectories.followSet to true to pack the targets of symbolic links. Withoutthis option, symbolic links are archived as such.noPaxSuppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.mtimeSet to aDateobject to force a specificmtimeforeverything added to the archive. Overridden bynoMtime.onWriteEntryCalled with eachWriteEntryorWriteEntrySyncthat is created in the course of writing thearchive.
Adds an entry to the archive. Returns the Pack stream.
Adds an entry to the archive. Returns true if flushed.
Finishes the archive.
Synchronous version ofPack.
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.
cwdExtract files relative to the specified directory. Defaultstoprocess.cwd(). If provided, this must exist and must be adirectory.filterA function that gets called with(path, entry)for eachentry being unpacked. Returntrueto unpack the entry from thearchive, orfalseto skip it.newerSet to true to keep the existing file on disk if it's newerthan the file in the archive.keepDo not overwrite existing files. In particular, if a fileappears more than once in an archive, later copies will notoverwrite earlier copies.preservePathsAllow 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.unlinkUnlink 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.stripRemove 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.umaskFilter the modes of entries likeprocess.umask().dmodeDefault mode for directoriesfmodeDefault mode for filesmaxMetaEntrySizeThe maximum size of meta entries that issupported. Defaults to 1 MB.preserveOwnerIf true, tar will set theuidandgidofextracted entries to theuidandgidfields 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-pintar(1), but ACLs and other system-specific data is never unpackedin this implementation, and modes are set by default already.win32True if on a windows platform. Causes behavior wherefilenames containing<|>?chars are converted towindows-compatible values while being unpacked.uidSet 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 theuidfield in the archive.Cannot be used along withpreserveOwner. Requires also setting agidoption.gidSet 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 thegidfield in the archive.Cannot be used along withpreserveOwner. Requires also setting auidoption.noMtimeSet to true to omit writingmtimevalue for extractedentries.transformProvide a function that takes anentryobject, 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, usethefilteroption described above.)strictTreat warnings as crash-worthy errors. Default false.onReadEntryA function that gets called with(entry)for each entrythat passes the filter.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")chmodSet 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 aprocessUmaskoptions is also provided. Otherwise tar willextract with whatever mode is provided, and let the processumaskapply normally.processUmaskSet to an explicit numeric value to avoidcallingprocess.umask()whenchmod: trueis set.maxDepthThe maximum depth of subfolders to extract into. Thisdefaults to 1024. Anything deeper than the limit will raise awarning and skip the entry. Set toInfinityto remove thelimitation.
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.
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.
Returns an event emitter that emitsentry events withtar.ReadEntry objects.
The following options are supported:
strictTreat warnings as crash-worthy errors. Default false.filterA function that gets called with(path, entry)for eachentry being listed. Returntrueto emit the entry from thearchive, orfalseto skip it.onReadEntryA function that gets called with(entry)for each entrythat passes the filter.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")
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:
extendedThe extended metadata object provided to the constructor.globalExtendedThe global extended metadata object provided to theconstructor.remainThe number of bytes remaining to be written into thestream.blockRemainThe number of 512-byte blocks remaining to be writteninto the stream.ignoreWhether this entry should be ignored.metaTrue 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 has
path,type,size,mode, and so on.
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:
pathThe path field that will be written to the archive. Bydefault, this is also the path from the cwd to the file systemobject.portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.myuidIf supported, the uid of the user running the currentprocess.myuserTheenv.USERstring if set, or''. Set as the entryunamefield if the file'suidmatchesthis.myuid.maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 1 MB.linkCacheA Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.statCacheA Map object that caches callslstat.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths.cwdThe current working directory for creating the archive.Defaults toprocess.cwd().absoluteThe absolute path to the entry on the filesystem. Bydefault, this ispath.resolve(this.cwd, this.path), but it can beoverridden explicitly.strictTreat warnings as crash-worthy errors. Default false.win32True 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.noPaxSuppress pax extended headers. Note that this means thatlong paths and linkpaths will be truncated, and large or negativenumeric values may be interpreted incorrectly.noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.
path is the path of the entry as it is written in the archive.
The following options are supported:
portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.maxReadSizeThe maximum buffer size forfs.read()operations.Defaults to 1 MB.linkCacheA Map object containing the device and inode value forany file whose nlink is > 1, to identify hard links.statCacheA Map object that caches callslstat.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths.cwdThe current working directory for creating the archive.Defaults toprocess.cwd().absoluteThe absolute path to the entry on the filesystem. Bydefault, this ispath.resolve(this.cwd, this.path), but it can beoverridden explicitly.strictTreat warnings as crash-worthy errors. Default false.win32True if on a windows platform. Causes behavior where pathsreplace\with/.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.umaskSet to restrict the modes on the entries in the archive,somewhat like how umask works on file creation. Defaults toprocess.umask()on unix systems, or0o22on Windows.
If strict, emit an error with the provided message.
Otherwise, emit a'warn' event with the provided message and data.
Synchronous version of tar.WriteEntry
A version of tar.WriteEntry that gets its data from a tar.ReadEntryinstead of from the filesystem.
readEntry is the entry being read out of another archive.
The following options are supported:
portableOmit metadata that is system-specific:ctime,atime,uid,gid,uname,gname,dev,ino, andnlink. Notethatmtimeis still included, because this is necessary for othertime-based operations. Additionally,modeis set to a "reasonabledefault" for most unix systems, based on aumaskvalue of0o22.preservePathsAllow absolute paths. By default,/is strippedfrom absolute paths.strictTreat warnings as crash-worthy errors. Default false.onwarnA function that will get called with(code, message, data)forany warnings encountered. (See "Warnings and Errors")noMtimeSet to true to omit writingmtimevalues for entries.Note that this prevents using other mtime-based features liketar.updateor thekeepNeweroption with the resulting tar archive.
A class for reading and writing header blocks.
It has the following fields:
nullBlockTrue if decoding a block which is entirely composed of0x00null bytes. (Useful because tar files are terminated byat least 2 null blocks.)cksumValidTrue if the checksum in the header is valid, falseotherwise.needPaxTrue if the values, as encoded, will require a Paxextended header.pathThe path of the entry.modeThe 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.uidNumeric user id of the file ownergidNumeric group id of the file ownersizeSize of the file in bytesmtimeModified time of the filecksumThe 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).typeThe human-readable name of the type of entry this represents,or the alphanumeric key if unknown.typeKeyThe alphanumeric key for the type of entry this headerrepresents.linkpathThe target of Link and SymbolicLink entries.unameHuman-readable user name of the file ownergnameHuman-readable group name of the file ownerdevmajThe major portion of the device number. Always0forfiles, directories, and links.devminThe minor portion of the device number. Always0forfiles, directories, and links.atimeFile access time.ctimeFile change time.
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 the provided buffer starting at the specified offset.
Buffer length must be greater than 512 bytes.
Set the fields in the data object.
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.
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.
globalTrue if this represents a global extended header, or falseif it is for a single entry.atimecharsetcommentctimegidgnamelinkpathmtimepathsizeuidunamedevinonlink
Set the fields set in the object.global is a boolean that defaultsto false.
Return a Buffer containing the header and body for the Pax extendedheader entry, ornull if there is nothing to encode.
Return a string representing the body of the pax extended headerentry.
Return a string representing the key/value encoding for the specifiedfieldName, or'' if the field is unset.
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.)
A translation table for thetype field in tar headers.
Get the human-readable name for a given alphanumeric code.
Get the alphanumeric code for a given human-readable name.
About
tar for node
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.