3.0.0 • Published 3 years ago

node-7z v3.0.0

Weekly downloads
7,855
License
ISC
Repository
github
Last release
3 years ago

Release Dependencies Status Linux Build Windows Build Code coverage Code Maintainability Known Vulnerabilities

Usage

import Seven from 'node-7z'

// myStream is a Readable stream
const myStream = Seven.extractFull('./archive.7z', './output/dir/', {
  $progress: true
})

myStream.on('data', function (data) {
  doStuffWith(data) //? { status: 'extracted', file: 'extracted/file.txt" }
})

myStream.on('progress', function (progress) {
  doStuffWith(progress) //? { percent: 67, fileCount: 5, file: undefinded }
})

myStream.on('end', function () {
    // end of the operation, get the number of folders involved in the operation
  myStream.info.get('Folders') //? '4'
})

myStream.on('error', (err) => handleError(err))

Table of content

Installation

npm install --save node-7z

You should have the a 7-Zip executable (v16.02 or greater) available in your system.

  • On Debian and Ubuntu install the p7zip-full package or use 7-Zip 21.02 alpha or higher
  • On Mac OSX use Homebrew brew install p7zip
  • On Windows get 7-Zip from 7-Zip download page.

By default the module calls the 7z binary, it should be available in your PATH.

An alternative 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 an archive.

ArgumentsTypeDescription
archivestringArchive to create
sourcestring\|string[]Source files to add to the archive. Multiple sources can be given using an Array
optionsObjectOptions object. Can be omitted
// adds all *.txt files from current folder and its subfolders to archive Files.7z.
const myStream = Seven.add('Files.7z', '*.txt', {
  recursive: true
})

Delete

Deletes files from an archive.

ArgumentsTypeDescription
archivestringArchive to target
targetstring\|string[]Target files to remove from the archive. Multiple targets can be given using an Array
optionsObjectOptions object. Can be omitted
// deletes *.bak files from archive archive.zip.
const myStream = Seven.delete('archive.zip', '*.bak')

Extract

Extracts files from an archive to the current directory or to the output directory. This command copies all extracted files to one directory.

ArgumentsTypeDescription
archivestringArchive to extract files from
outputstringOutput directory
optionsObjectOptions object. Can be omitted
// extracts all *.cpp files from archive archive.zip to c:\soft folder.
const myStream = Seven.extract('archive.zip', 'c:/soft', {
  recursive: true,
  $cherryPick: '*.cpp'
})

Extract with full paths

Extracts files from an archive with their full paths in the current directory, or in an output directory if specified.

ArgumentsTypeDescription
archivestringArchive to extract files from
outputstringOutput directory
optionsObjectOptions object. Can be omitted
// extracts all *.cpp files from the archive archive.zip to c:\soft folder.
const myStream = Seven.extractFull('archive.zip', 'c:/soft', {
  recursive: true,
  $cherryPick: '*.cpp'
})

Hash

Calculates hash values for files.

ArgumentsTypeDescription
targetstring\|string[]Target files to calculate the hash of. Multiple targets can be given using an Array
optionsObjectOptions object. Can be omitted
// calculates SHA256 for a.iso.
const myStream = Seven.hash('a.iso', {
  hashMethod: 'sha256'
})

List

Lists contents of an archive.

ArgumentsTypeDescription
archivestringArchive to list the file from
optionsObjectOptions object. Can be omitted
// list all the *.txt and *.js files in archive.zip
const myStream = Seven.list('archive.zip', {
  $cherryPick: ['*.txt*', '*.js'],
})

Rename

Renames files in an archive.

ArgumentsTypeDescription
archivestringArchive to target
targetArray[string[]]Pair of target/new names files to remove rename. Multiple targets can be given using an Array
optionsObjectOptions object. Can be omitted
// renames old.txt to new.txt and 2.txt to folder\2new.txt .
const myStream = Seven.rename('a.7z', [
  ['old.txt', 'new.txt'],
  ['2.txt', 'folder/2new.txt']
])

Test integrity

Tests archive files.

ArgumentsTypeDescription
archivestringArchive to test
optionsObjectOptions object. Can be omitted
// tests *.doc files in archive archive.zip.
const myStream = Seven.list('archive.zip', {
  recursive: true,
  $cherryPick: '*.doc'
})

Update

Updates older files in the archive and adds files that are not already in the archive.

ArgumentsTypeDescription
archivestringArchive to create
sourcestring\|string[]Source files to update from the file-system to the archive. Multiple sources can be given using an Array
optionsObjectOptions object. Can be omitted
// updates *.doc files to archive archive.zip.
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

NameTypeDescriptionSwitches
alternateStreamExtractboolean"Extract file as alternate stream, if there is ':' character in name"-snc
alternateStreamReplacebooleanReplace ':' character to '_' character in paths of alternate streams-snr
deleteFilesAfterbooleanDelete files after compression-sdel
fullyQualifiedPathsbooleanUsefully qualified file paths-spf
hardlinksbooleanStore hard links as links (WIM and TAR formats only)-snh
largePagesbooleanSet Large Pages mode-spl
latestTimeStampbooleanSet archive timestamp from the most recently modified file-stl
noArchiveOnFailbooleanStop archive creating, if 7-Zip can't open some input file.-sse
noRootDuplicationbooleanEliminate duplication of root folder for extract command-spe
noWildcardsbooleanDisable wildcard matching for file names-spd
ntSecuritybooleanStore NT security-sni
sortByTypebooleanSort files by type while adding to solid 7z archive-mqs
openFilesbooleanCompress files open for writing-ssw
recursivebooleanRecurse subdirectories. For -r0 usage see raw-r
symlinksbooleanStore symbolic links as links (WIM and TAR formats only)-snl
techInfobooleanShow technical information-slt
timeStatsbooleanShow execution time statistics-bt
toStdoutbooleanWrite data to stdout-so
yesbooleanAssume Yes on all queries-y
alternateStreamStorebooleanStore NTFS alternate Streams-sns
caseSensitivebooleanSet Sensitive Case mode-ssc
archiveNameModestringSet Archive name mode-sa
archiveTypestringType of archive-t
cpuAffinitystringSet CPU thread affinity mask (hexadecimal number).-stm
excludeArchiveTypestringExclude archive type-stx
fromStdinstringRead data from StdIn-si
hashMethodstringSet hash function-scrc
listFileCharsetstringSet charset for list files-scs
logLevelstringSet output log level-bb
multiBlockSizestringCreates multi-block xz archives of [Size]m\|g block size-ms
outputDirstringSet Output directory-o
overwritestringOverwrite mode-ao
passwordstringSet Password-p
sfxstringCreate SFX archive-sfx
updateOptionsstringUpdate options-u
workingDirstringSet Working directory-w
excludeArchivestring[]Exclude archive filenames-ax
excludestring[]Exclude filenames-x
includestring[]Include filenames-i
includeArchivestring[]Include archive filenames-ai
methodstring[]Set Compression Method-m
outputStreamsstring[]Set output stream for output/error/progress-bs
volumesstring[]Create Volumes-v

Special options

Those options are not provided by 7-Zip but are features of this module.

NameTypeDescription
$progressbooleanProgress percentage gets fired. Shortcut for { outputStreams: ['b1'] } Use if you want access to the progress event. Has an impact on performances.
$deferbooleanCreate the stream but do not spawn child process
$childProcessChildProcessAttach an external child process to be parsed
$binstringPath to an other 7-Zip binary. Default: 7z
$cherryPickstring[]Some commands accepts more specific targets, see example above
$rawstring[]Pass raw arguments to the child_process.spawn()command
$spawnOptionsObjectPass options 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)
  // {
  //   file: 'path/of/the/file/in/the/archive',
  //   status: 'renamed|tested|updated|skipped|deleted|extracted',
  //   attributes: '....A', size: 9, sizeCompressed: 3, (only list command)
  //   hash: 'FEDC304F', size: 9 (only hash command)
  //   techInfo: Map(8) { (only list command with `techInfo` switch)
  //      'Path' => 'DirHex/sub2/e825776890f2b',
  //      'Size' => '9',
  //      'Modified' => '2018-09-29 09:06:15',
  //      'Attributes' => 'A_ -rw-r--r--',
  //      'CRC' => 'FEDC304F',
  //      'Encrypted' => '-',
  //      'Method' => 'LZMA2:12',
  //      'Block' => '0'
  //   }
  // }
})

Event: end

An .info proprety can contain meta-data (type Map)

myStream.info
// Map {
//   '7-Zip [64] 16.02 ' => 'Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21',
//   'Creating archive' => './test/_tmp/txt-and-md-only.7z',
//   'Items to compress' => '6',
//   'Files read from disk' => '6',
//   'Archive size' => '212 bytes (1 KiB)' }

Event: error

mySevenStream.on('error', function (err) {
  // a standard error
  // `err.stderr` is a string that can contain extra info about the error
})

Advanced usage

Compression method

Using the CLI, compression is done like this:

# adds *.exe and *.dll files to solid archive archive.7z using LZMA method
# with 2 MB dictionary and BCJ filter.
7z a archive.7z *.exe -m0=BCJ -m1=LZMA:d=21

Using this module:

const compress = Seven.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.

const compress = Seven.add('archive.7z', '*.gif', {
  $raw: [ '-i!*.jpg', '-i!*.png' ], // only images
})

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 7-Zip 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 = // an external child process
const myStream = Seven.add('dummy', 'dummy', {
  $defer: true
})
myStream.on('data', data => yourLogicWith(data))
Seven.listen(myStream)

With :heart: from quentinrossetti

3.0.0

3 years ago

2.1.2

4 years ago

2.1.1

4 years ago

2.1.0

4 years ago

2.0.5

4 years ago

2.0.4

4 years ago

2.0.3

5 years ago

2.0.0

5 years ago

2.0.1

5 years ago

2.0.2

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.4.0

8 years ago

0.3.0

9 years ago

0.2.0

10 years ago

0.1.3

10 years ago

0.1.2

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago