node-7z
A Node.js wrapper for 7-Zip
Usage
import Seven from 'node-7z'
const myStream = Seven.extractFull('./archive.7z', './output/dir/')
.on('data', function (data) {
doStuffWith(data)
})
.on('progresss', function (progress) {
doStuffWith(progress)
})
.on('end', function () {
myStream.info.get('Folders')
})
.on('error', (err) => handleError(err))
Table of content
Installation
npm install --save node-7z
You should have the a 7-Zip executable (v16.04 or greater) available in your system.
- On Debian and Ubuntu install the p7zip-full package.
- On Mac OSX use Homebrew
brew install p7zip
- On Windows get 7-Zip frome 7-Zip download page.
By default the module calls the 7z
binary, it should be available in your
PATH.
An alernative is to add the 7zip-bin
module to your project. This module
contains an up-to-date version of 7-Zip for all available plaforms. Then you
can do:
import sevenBin from '7zip-bin'
import { extractFull } from 'node-7z'
const pathTo7zip = sevenBin.path7za
const seven = extractFull('./archive.7z', './output/dir/', {
$bin: pathTo7zip
})
API
See the 7-Zip documentation
for the full list of usages and options (switches).
Commands
Add
Adds files to archive.
Arguments | Type | Description |
---|
archive | string | Archive to create |
source | `string | string[]` |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.add('Files.7z', '*.txt', {
recursive: true
})
Delete
Deletes files from archive.
Arguments | Type | Description |
---|
archive | string | Archive to target |
target | `string | string[]` |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.delete('archive.zip', '*.bak')
Extracts files from an archive to the current directory or to the output directory. This command copies all extracted files to one directory.
Arguments | Type | Description |
---|
archive | string | Archive to extract files from |
output | string | Output directory |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.extract('archive.zip', 'c:/soft', {
recursive: true,
$cherryPick: '*.cpp'
})
Extracts files from an archive with their full paths in the current directory, or in an output directory if specified.
Arguments | Type | Description |
---|
archive | string | Archive to extract files from |
output | string | Output directory |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.extractFull('archive.zip', 'c:/soft', {
recursive: true,
$cherryPick: '*.cpp'
})
Hash
Calculate hash values for files.
Arguments | Type | Description |
---|
target | `string | string[]` |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.hash('a.iso', {
hashMethod: 'sha256'
})
List
Lists contents of archive.
Arguments | Type | Description |
---|
archive | string | Archive to list the file from |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.list('archive.zip', {
$cherryPick: ['*.txt*', '*.js'],
})
Rename
Renames files in archive.
Arguments | Type | Description |
---|
archive | string | Archive to target |
target | Array[string[]] | Pair of target/new names files to remove rename. Multiple targets can be given using an Array |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.rename('a.7z', [
['old.txt', 'new.txt'],
['2.txt', 'folder/2new.txt']
])
Test integrity
Tests archive files.
Arguments | Type | Description |
---|
archive | string | Archive to test |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.list('archive.zip', {
recursive: true,
$cherryPick: '*.doc'
})
Update
Update older files in the archive and add files that are not already in the archive.
Arguments | Type | Description |
---|
archive | string | Archive to create |
source | `string | string[]` |
[options] | Object | Options object. Can be omitted |
const myStream = Seven.add('archive.zip', '*.doc')
Options
Switches
In the 7-Zip world, command flags are called switches. In order to use them you can pass their name and value in the Options object
Name | Type | Description | Switches |
---|
alternateStreamExtract | boolean | "Extract file as alternate stream, if there is ':' character in name" | -snc |
alternateStreamReplace | boolean | Replace ':' character to '_' character in paths of alternate streams | -snr |
deleteFilesAfter | boolean | Delete files after compression | -sdel |
fullyQualifiedPaths | boolean | Usefully qualified file paths | -spf |
hardlinks | boolean | Store hard links as links (WIM and TAR formats only) | -snh |
largePages | boolean | Set Large Pages mode | -spl |
latestTimeStamp | boolean | Set archive timestamp from the most recently modified file | -stl |
noRootDuplication | boolean | Eliminate duplication of root folder for extract command | -spe |
noWildcards | boolean | Disable wildcard matching for file names | -spd |
ntSecurity | boolean | Store NT security | -sni |
openFiles | boolean | Compress files open for writing | -ssw |
recursive | boolean | Recurse subdirectories. For -r0 usage see raw | -r |
symlinks | boolean | Store symbolic links as links (WIM and TAR formats only) | -snl |
techInfo | boolean | Show technical information | -slt |
timeStats | boolean | | -bt |
toStdout | boolean | Write data to stdout | -so |
yes | boolean | Assume Yes on all queries | -y |
alternateStreamStore | boolean | Store NTFS alternate Streams | -sns |
caseSensitive | boolean | Set Sensitive Case mode | -ssc |
archiveNameMode | string | Set Archive name mode | -sa |
archiveType | string | Type of archive | -t |
cpuAffinity | string | Set CPU thread affinity mask (hexadecimal number). | -stm |
excludeArchiveType | string | Exclude archive type | -stx |
fromStdin | string | Read data from StdIn | -si |
hashMethod | string | Set hash function | -scrc |
listFileCharset | string | Set charset for list files | -scs |
logLevel | string | Set output log level | -bb |
outputDir | string | Set Output directory | -o |
overwrite | string | Overwrite mode | -ao |
password | string | Set Password | -p |
sfx | string | Create SFX archive | -sfx |
updateOptions | string | Update options | -u |
workingDir | string | Set Working directory | -w |
excludeArchive | string[] | Exclude archive filenames | -ax |
exlude | string[] | Exclude filenames | -x |
include | string[] | Include filenames | -i |
includeArchive | string[] | Include archive filenames | -ai |
method | string[] | Set Compression Method | -m |
outputStreams | string[] | Set output stream for output/error/progress | -bs |
volumes | string[] | Create Volumes | -v |
Special options
Those options are not provided by 7-Zip but are features of this module.
Name | Type | Description |
---|
$progress | boolean | Progress percentage gets fired. Shortcut for { outputStreams: ['b1'] } |
$defer | boolean | Create the stream but do not spawn child process |
$childProcess | ChildProcess | Attach an external child process to be parsed |
$bin | string | Path to an other 7-Zip binary. Default: 7z |
$cherryPick | string[] | Some commands accepts more specific targets, see example above |
$raw | string[] | Pass raw arguments to the child_process.spawn() command |
Events
Event: data
The data
event is emitted for each processed file. The payload is an object. WARNING only the data.file
proprety is guaranteed to be present
mySevenStream.on('data', function (data) {
console.log(data)
})
Event: end
An .info
proprety can contain meta-data (type Map)
myStream.info
Event: error
mySevenStream.on('error', function (err) {
})
Advanced usage
Compression method
Using the CLI, compression is made like that:
7z a archive.7z *.exe -m0=BCJ -m1=LZMA:d=21
With to module you can translate it like that:
import { add } from 'node-7z'
const myCompressStream = new add('archive.7z', '*.exe', {
method: ['0=BCJ', '1=LZMA:d=21']
})
Raw inputs
Thanks to sketchpunk #9 for this one
Sometimes you just want to use the lib as the original command line. For
instance you want to apply to switches with different values. You can use the
custom $raw
key in your options
object and pass it an Array of
values.
import { add } from 'node-7z'
const myCompressStream = new add('archive.7z', '*.gif', {
$raw: [ '-i!*.jpg', '-i!*.png' ],
})
Emoji and Unicode
Due to a 7z
limitation emojis and special characters can't be used as values
when passed to an option
object (ex: password). But they can be used in
archive, filenames and destinations.
Use the { charset: 'UTF-8' }
for special characters.
Log level
The default log level (-bb
switch) is set to:
3 :show information about additional operations (Analyze, Replicate) for "Add" / "Update" operations.
It's a base feature of node-7z
and is required for the module to work as
expected. A diffrent value should not be used.
Security
Values given by the package are not sanitized, you just get the raw output from
the 7z
binary. Remember to never trust user input and sanitize accordingly.
External child process
You can pipe a child procress from an other source and pass it to node-7z
. An
use case may be that the 7-Zip process runs on an other machine and the sdtio is
piped in the application.
const external =
const myStream = Seven.add('dummy', 'dummy', {
$defer: true
})
myStream.on('data', data => yourLogic())
Seven.listen(myStream)
With :heart: from quentinrossetti