Giter Site home page Giter Site logo

node-7z's Introduction

node-7z

A Node.js wrapper for 7-Zip

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.

Arguments Type Description
archive string Archive to create
source string|string[] Source files to add to the archive. Multiple sources can be given using an Array
[options] Object Options 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.

Arguments Type Description
archive string Archive to target
target string|string[] Target files to remove from the archive. Multiple targets can be given using an Array
[options] Object Options 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.

Arguments Type Description
archive string Archive to extract files from
output string Output directory
[options] Object Options 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.

Arguments Type Description
archive string Archive to extract files from
output string Output directory
[options] Object Options 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.

Arguments Type Description
target string|string[] Target files to calculate the hash of. Multiple targets can be given using an Array
[options] Object Options object. Can be omitted
// calculates SHA256 for a.iso.
const myStream = Seven.hash('a.iso', {
  hashMethod: 'sha256'
})

List

Lists contents of an archive.

Arguments Type Description
archive string Archive to list the file from
[options] Object Options 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.

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
// 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.

Arguments Type Description
archive string Archive to test
[options] Object Options 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.

Arguments Type Description
archive string Archive to create
source string|string[] Source files to update from the file-system to the archive. Multiple sources can be given using an Array
[options] Object Options 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

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
noArchiveOnFail boolean Stop archive creating, if 7-Zip can't open some input file. -sse
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
sortByType boolean Sort files by type while adding to solid 7z archive -mqs
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 Show execution time statistics -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
multiBlockSize string Creates multi-block xz archives of [Size]m|g block size -ms
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
exclude 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'] } Use if you want access to the progress event. Has an impact on performances.
$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
$spawnOptions Object Pass 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 all .exe files to solid archive archive.7z using the 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']
})

Encrypt metadata (hide filenames in password protected archives)

This operation is supported only in the 7z file format. Using the CLI, if you want to password protect an archive while also hiding filenames you write:

# adds all .exe files with a password and also encrypt metadata, thus hiding filenames
7z a archive.7z *.exe -p -mhe

Using this module:

const compress = Seven.add('archive.7z', '*.exe', {
  password: "your-password-here",
  method: ['he']
})

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 โค๏ธ from quentinrossetti

node-7z's People

Contributors

abaltra avatar abdelghaniitassi avatar abdelghanitassi avatar atomicpages avatar bondden avatar brickyang avatar bulentv avatar ciaranj avatar colin969 avatar curiousdannii avatar dependabot[bot] avatar jhack-jos avatar jliben avatar jmopel avatar kljh avatar lbeschastny avatar m59peacemaker avatar mansurt avatar mnatsu31 avatar mzehrer avatar pixelastic avatar q2s2t avatar redx25 avatar royalgamer06 avatar sketchpunk avatar snyk-bot avatar thetechstech avatar toantk911 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

node-7z's Issues

Adobe-CEP - Syntax-Error: Unexpected token

In:

...\CEP\extensions\com.atrocty.ExSphax\node_modules\node-7z\src\flags.js:9

Uncaught SyntaxError: Unexpected token ...
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:567:28)
    at Object.Module._extensions..js (module.js:610:10)
    at Module.load (module.js:512:32)
    at tryModuleLoad (module.js:471:12)
    at Function.Module._load (module.js:463:3)
    at Module.require (module.js:522:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (...\CEP\extensions\com.atrocty.ExSphax\node_modules\node-7z\src\main.js:4:15)

I am enforced to use this Node.js 7.7.4:
https://github.com/Adobe-CEP/CEP-Resources/blob/master/CEP_8.x/Documentation/CEP%208.0%20HTML%20Extension%20Cookbook.md#chromium-embedded-framework-cef

Is it possible to replace that token? Seems like ES6 doesn't support this kind of token.

Error while creating the zip on ubuntu?

Hi,

I created a small app to be deployed on bluemix. I needed to download the ubuntu package and integrate with my nodejs app. I also set the path to the bin directory. but then I get the below error

2016-04-14T12:45:09.38+0100 [App/0] ERR Potentially unhandled rejection
[2] undefined (WARNING: non-Error used)

Here is my code:-
var express = require('express');
var fs = require('fs');
var path = require('path');
var cfenv = require('cfenv');
var envPath = __dirname;
if (envPath.indexOf('7z') < 0) {
var _7zipPath = path.join(process.cwd(), '/bin');
process.env.PATH += (envPath[envPath.length -1] === ';') ? _7zipPath : ';' + _7zipPath;
}
var Zip = require('node-7z');
var archive = new Zip();
archive.add("/home/vcap/app/archive.zip", "/home/vcap/app/README.md", {p: "manish"}).then(function () {
});

Also below is the structure of my directory

3bc1c96b95ad0710

Any help is appreciated

extracting to fileshare not supported

Hi,

Is it possible to support the extraction of files from and to fileshares?

If I use zip.ExtractFull ('//servername/sharename/folder/zipfile.zip', '//servername/sharename/folder'), I get "The system cannot find the path specified". Extracting it to a local path works fine.

Is it possible to add the support for UNCs?

Thanks,

SyntaxError: Invalid regular expression

const BODY_PROGRESS = new RegExp('^ (?\d+)% ?(?\d+)? ?(?.)$')
^

SyntaxError: Invalid regular expression: /^ (?\d+)% ?(?\d+)? ?(?.)$/: Invalid group
at new RegExp ()
at Object. (C:\Users\xxx\AppData\Roaming\npm\node_modules\node-7z\src\regexp.js:16:23)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object. (C:\Users\xxx\AppData\Roaming\npm\node_modules\node-7z\src\parser.js:16:97)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)

API should have the ability to not touch the filesystem

I've come to understand that pretty much no module should be reading the filesystem directly. The reason is because is severely limits its practicality and/or efficiency. For example, what if you're downloading the file from the internet? There may be no reason to save it to disk, rather you might want to use a stream.

So I'm recommending that this module be amended to support streams and regular strings in addition to filenames.

Error linking 7zip during install

Hello,

the npm install works fine on macos but it fails on ubuntu (where p7zip-full is installed and the command 7z running)

npm WARN package.json [email protected] No repository field.
npm ERR! Linux 4.0.9-boot2docker
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "node-7z"
npm ERR! node v4.1.1
npm ERR! npm  v2.14.4
npm ERR! path ../win-spawn/bin/win-spawn
npm ERR! code EPROTO
npm ERR! errno -71
npm ERR! syscall symlink

npm ERR! EPROTO: protocol error, symlink '../win-spawn/bin/win-spawn' -> '/open-moulinette/insee-iris/node_modules/node-7z/node_modules/.bin/win-spawn'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /open-moulinette/insee-iris/npm-debug.log

Version of 7z.exe must be v9.XX

I spent a few hours wondering why this worked just fine on my Linux system but failed on Windows.

On windows it returned no files having been extracted even though when I looked at the output folder there they were.

Turned out I have 7z.exe v16.04 on the windows machine. The v15.XX and up do not report their progress to stdout like v9.XX as "Extracting " so the 7z succeeds, but node-7z module is unable to capture the list of extracting files from stdout.

Not really an error as such, but thought it may be worth adding into the readme.

Unsupported Method

When trying to use it with a zip file created using some "unknown" program the 7z extract seems to succeed but returns the filename in .progress() in the form:

The Punisher (2016-) 001-000.jpg     Unsupported Method

Which is from the direct output from 7z x

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=en_GB.UTF-8,Utf16=on,HugeFiles=on,4 CPUs)

Processing archive: The Punisher 001 (2016) (digital) (Oroboros-DCP).cbr

Extracting  The Punisher (2016-) 001-000.jpg     Unsupported Method
Extracting  The Punisher (2016-) 001-001.jpg     Unsupported Method
Extracting  The Punisher (2016-) 001-002.jpg     Unsupported Method
Extracting  The Punisher (2016-) 001-003.jpg     Unsupported Method
Extracting  The Punisher (2016-) 001-004.jpg     Unsupported Method

Is there any way it could trigger an error to be handled with .catch()?

Is this module dead?

There was no recent activity. Most of the dependancies are outdated. Is this module dead?

Spaces in path

Hello!
I have noticed that files with paths that contain a space are not working with this library.
For example, these won't work:

SevenZip.extractFull('fi le.zip', 'file');
SevenZip.extractFull('file.zip', 'fi le');
SevenZip.extractFull('Program Files\\file.zip', 'file');

The problem is caused by this line:
https://github.com/quentinrossetti/node-7z/blob/master/util/run.js#L22

It splits the arguments to 7za by spaces, and if a path contains spaces it will split it to multiple arguments which won't work.

Is this something that can be fixed?
Thanks

Opens command prompt and logs everything there instead of error or progress

Hi,

I am able to successfully extract a .7z file. However, I cannot seem to capture any error, progress or data, as the spawn command opens everything in a separate cmd window.

extract7z_stream = Seven.extractFull(filePath, outputPath, { $progress: true }); extract7z_stream.on('error', (err) => { console.log(err, " in extraction 7zip"); }); extract7z_stream.on('end', () => { console.log("all done") }); extract7z_stream.on('progress', (progress) => { console.log(progress); });

**Expected Behavior: ** See everything in dev tools window.

**Current Behavior: ** Opens command prompt window and stdouts everything there.
As shown in the image.
cmd_out

*Edit: Any help would be appreciated. Thank-you.

Hangs on encrypted archive without supplied password

I'm not sure if this is an issue with this package or if 7z simply doesn't support this but from time to time I get archives with passwords that I don't have (i.e. I don't have the password for the archive). When I try to either test or extract one of those archives node-7z simply hangs instead of failing gracefully.

Is there a way to implement this or do you know of a way to check wether or not an archive is password protected before running it through node-7z?

Getting ".then is not a function

I am using node-7z together with 7zip-bin to sequentially process some archive files in my Electron (node.js) application. The issue I have is that I get the above error when I try to run my code. I have searched for a solution but so far been unable to find one. The code in questions is:

function processArchive(pdscQueue, archiveFilename, repoPath) {
    let tempFolder = tmp.dirSync() ;
    let devicePackFile = path.join(repoPath,archiveFilename) ;   // Create a temp folder for the extacted data
    sevenZip.extractFull(devicePackFile, tempFolder.name, { $bin: pathTo7zip})
    
    .then( function () {
        //
        // Process this file
        //
        tempFolder.removeCallback() ;   // Clean up
        //
        // Check if there are more to process
        //
        if ( pdscQueue.isEmpty()) {
            return ;
        } else {
            processArchive(pdscQueue, pdscQueue.dequeue(), repoPath ) ;
        }
    });
}

I hope you can help me, thanks for this nice package.

Extract/Extract full few files in 7z archive

i need some help to make extract/extract full with filename or fileext filter.

i try use { p: '.png}, and { ax : '.png'} for exclude files, but not work., ref 7zip api document

version 0.3.0. wildcards

quentin, thanks a lot.
but
this .... wildcards: [ '.txt', '.md' ] ... don't work.
this .... wildcards: '*.txt' .... work for me.

Error: spawn 7z ENOENT

events.js:154
throw er; // Unhandled 'error' event

Error: spawn 7z ENOENT
at exports._errnoException (util.js:890:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:182:32)
at onErrorNT (internal/child_process.js:348:16)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)

Wildcards problem

I found a problem which if I pass more than one value in wildcards, it doesn't work.
For example, if i want to extract selected files
wildcards: [ 'test.txt' ]
This above, works, but the below option doesn't.
wildcards: [ 'test.txt', 'test2.txt' ]

So i've made a change to make it work for me:
util/switches.js in line 38:

Before:

if (s === 'wildcards') {
     a.unshift(switches.wildcards);
}

After:

if (s === 'wildcards') {
     switches.wildcards.forEach(function(wildvalue, index){ a.unshift(wildvalue); });
}

Moved project to another computer and extractFull method throws an error

I am running into a strange error and wonder if anyone can help me.

I moved my project to another computer, the entire file structure with the 7z.exe included in it. I also copied my node-modules folder containing the node-7z folder in it. However when my code tries to extract it does not work it throws an error but when it tries to catch it, the error is undefined. I tried with using the 7z.exe itself and it did the job correctly, it is just the code that does not used the extractFull method correctly, although it was working correctly on my old computer. Any help would be appreciated!

Problems with typescript

I'm having trouble using this with typescript.
I had to do some changes in the way to include it but after being able to import everything it fails when I try to use it.

import Seven = require('node-7z');
import { path7za } from '7zip-bin'

const seven = new Seven();
const stream = seven.extractFull(
            './example.7z',
            './',
            {
                $bin: path7za
            }
        ).then(resp => {
            console.log('finish', resp);
        })

Error in (undefined) /node-7z/src/flags.js
Module parse failed: node_modules/node-7z/src/flags.js Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (9:15)
@ ./~/node-7z/src/main.js 4:14-32

Error in (undefined) /node-7z/src/commands.js
Module parse failed: node_modules/node-7z/src/commands.js Unexpected token (2:10)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:10)
@ ./~/node-7z/src/main.js 10:17-38

Thanks for the help

Error reporting is broken

It looks like latest 7zip versions report errors to stderr while node-7z looks for them in stdout.

This result in non-error Promise rejections (due to run.js#L94).

Error: spawn 7z ENOENT

I want to use node-7z on CentOS. I have tested my app on Mac and it works. When I ran the app on server, it throws an error about

Error: spawn 7z ENOENT
    at exports._errnoException (util.js:860:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at doNTCallback2 (node.js:450:9)
    at process._tickDomainCallback (node.js:405:17)

I saw this error once on my Mac. The reason for that is I forgot to install 7z on Mac. So I suppose this error stated the module can't find 7z command but I have already installed 7zip from http://netix.dl.sourceforge.net/project/p7zip/p7zip/15.09/p7zip_15.09_src_all.tar.bz2 and set the $PATH and alias in ~/.bashrc:

export PATH=/data/node/mongodb/bin:/usr/local/bin/:$PATH
alias 7z='7za'

I can run 7z a command on shell.

The path of 7z is /usr/local/bin/7za.

Error while creating the zip on ubuntu and windows?

Hi,

I created a small app to be deployed on bluemix. I needed to download the ubuntu package and integrate with my nodejs app. I also set the path to the bin directory. but then I get the below error

2016-04-14T12:45:09.38+0100 [App/0] ERR Potentially unhandled rejection
[2] undefined (WARNING: non-Error used)

Here is my code:-
var express = require('express');
var fs = require('fs');
var path = require('path');
var cfenv = require('cfenv');
var envPath = __dirname;
if (envPath.indexOf('7z') < 0) {
var _7zipPath = path.join(process.cwd(), '/bin');
process.env.PATH += (envPath[envPath.length -1] === ';') ? _7zipPath : ';' + _7zipPath;
}
var Zip = require('node-7z');
var archive = new Zip();
archive.add("/home/vcap/app/archive.zip", "/home/vcap/app/README.md", {p: "manish"}).then(function () {
});

Also below is the structure of my directory

3bc1c96b95ad0710

Any help is appreciated

[question] list doesn' work

const _7z = require('node-7z');
const myStream = _7z.list('C:\\Downloads.zip',  
                                          { recursive: true, "$cherryPick": ['*.txt*', '*.js'] });
const _data = [];
myStream
.on('data', function(d){
	console.log(d);
	_data.push(d);
})
.on('end', function (d) {
  	console.log("end", _data);
  	res.send({_data, info: myStream.info});
}).on('error', function (d) {
  	console.log("error:", d);
  	res.send(d);
})

Excuse me, could you take a look?
I can see a pop console windows, it shows the content. But the data is empty.
When I run the _7z.extractFull, it extracts the file. But the console data does not goes to data either.

add an option to supply 7z path

Hi,

This option can be very useful if I'm delivering my app to other computer that don't necessarily have 7zip installed. If there was such option, anyone could just specify the 7z path (even with installing https://github.com/fritx/win-7zip as a dependency).
Or maybe an option to download 7zip with that module!

what do you think?

7z list bug with no datetime info

I found a bug in list in files which doesn't have date/time info, it's not usual i think, but i've found files like these:
7z_stdout.txt

I have made a fix in the file "lib/list.js" that worked for me:
Line 23: var regex = /([\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}]+) ([.DA]+) +(\d+)[ \d]+ (.+)/;
Line 56: if(parseInt(res[1])){ var return_date = new Date(res[1]); }
Line 57: else{ var return_date = ""; }
Line 58: var e = {
Line 59: date: return_date,

The changed file:
list.txt

progress callback is not working

I tried to count the number of extracted files using the progress callback like this ;

.progress(function (files) {
        console.log('Some files are extracted: %s', files);
        filesNumber += files.length ;
})

At end the value of filesNumber is 0 even though i have 16 files in the generated directory.
I think it depends on whether 7z generates an output or not

Help with fromStdin

Hello, first of all amazing library!

I'm working in a scenario that it's not desirable to have any files in disc, so I'm trying to use the options "toStdout" and "fromStdin"

I had success using only "toStdout" but loading the data from a file on the disc (helped me a lot) but I'm having problem when combing both options...

This is my code (more or less) ....

        const sevenStream = Seven.extractFull(null, null, {
            $bin: pathTo7zip,
            toStdout: true,
            fromStdin: '',
          });

          const { _childProcess: childProcess } = sevenStream;

          // piping a readableStream that contains the data for a compressed file into childProcess.stdin
          readableStream.pipe(childProcess.stdin);
          
         // here I'm trying to extract the de-compressed information from 
         // childProcess.stdout ...
         // this code works fine if I load the data from a disc file (instead of stdin)
         childProcess.stdout.setEncoding('utf8');

          let chunkHolder = '';

          childProcess.stdout.on('data', (chunk) => {
            console.log(`Received ${chunk.length} bytes of data.`);
            chunkHolder += chunk;
          });

          return childProcess.stdout.on('end', async () => {
            console.log('uploading file from childProcess.stdout...', { uploadPath, inboundBucket });
            await s3.uploadS3Content(chunkHolder, uploadPath, inboundBucket);

            // Delete file from the FTP server
            console.log('deleting FTP file...', { ftpPath });
            await FTP.deleteFile(ftpPath);

            return innerResolve();
          });

Use 7z in 7za place

I need unpack JDK8.exe but 7za.exe don't do the magic, then I need to use 7z.exe and 7z.dll...

As a workaround I put 7z.dll and 7z.dll in my application root and rename the binary 7z.exe to 7za.exe

The solution works well , but a better solucion should be written

the module shows FileSystemProvider: Invalid name:

Hi, how are you ?

I have this code on node, it works good, but before the End 7zip, show: FileSystemProvider: Invalid name:

do you know why ??

The module is still in development, can I use it without problem ?

Regards
Eduardo

/*
probando 7-Zip
*/
var archives = new Zip();
archives.add('archives.7z', ['../storage/nah1/vol2/115000/Anexo A.PDF'], {
m0: '=BCJ',
m1: '=LZMA:d=21'
})
.then(function () {
console.log("End 7zip.");
// Do stuff...
});

Can't get extraction to work

I can't figure this out any ideas?

file:///node_modules/node-7z/src/regexp.js:1
SyntaxError: Invalid regular expression: /^ *(?<percent>\d+)% ?(?<fileCount>\d+)? ?(?<file>.*)$/: Invalid group
    at Object.<anonymous> (file:///node_modules/node-7z/src/regexp.js:2:30)
    at Generator.next (<anonymous>)

ExtractFull progress file array remains empty

I am using the following code:

var archive = new Zip();
archive.extractFull('c:\\archive.rar', 'c:\\destination', {
 wildcard: ['*.jpg', '*.png'],
  r: true 
})
.progress(function (files) {
  // Do stuff with files...
})
.then(function () {
  // Do stuff...
});

The file is extracted successfully but the files array of the progress function remains empty

remove polyfill

I was unable to use this package due to its use of a polyfill. It somehow conflicted with Meteor and caused the app to be unable to run. I forked it and replaced the polyfill with a local reference that serves the same purpose, via this:

const RegExp = (() => {
	try {
		new RegExp('(?<test>a)')
		return RegExp
	} catch (error) {
		return require('named-regexp-groups')
	}
})()

Would you accept that as a PR?

Error: spawn ENOENT

Here is the code that I'm trying to run on my Mac:

var Zip = require('node-7z');
var archive = new Zip();
archive.list('testArchive.7z', {})
.progress(function (files) {
// Do stuff with files...
})
.then(function () {
// Do stuff...
});

I get this error:

events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)

Any ideas how to resolve this?

Thanks

The list command assumes there will be digits in the Compressed Column

I have a .cbr (.rar) file that has the following output when the list command is called:

Date Time Attr Size Compressed Name


2015-03-22 08:17:19 D.... 0 0 Accident
2013-03-08 11:12:12 ....A 255286 5945700 Accident/001.jpg
2013-03-08 11:12:12 ....A 259421 Accident/002.jpg
2013-03-08 11:12:12 ....A 221211 Accident/003.jpg
2013-03-08 11:12:12 ....A 173991 Accident/004.jpg

.... + 21 more files...

This archive (for whatever reason) does not display the compressed size of each file. Instead it displays the total compressed size of the archive in the first file's Compressed column.

This causes the list command to only return an array containing two items: the folder and the first file.

By changing the regex var in the lib/list.js module
to:
var regex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([.DA]+) +([\d\s]+) +\d+ +(.+)/;
from:
var regex = /(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([.DA]+) +(\d+) +\d+ +(.+)/;

to tell it to look for one or more digits or spaces...

The code now returns the complete list of 25 files. It also works for archives which have digits in the Compressed column.

Error when installing: p7zip-16.02 returns 14615 segmentation fault

Hi all. I am using node v10.15.3 and npm v6.9.0 on Mac OS Mojave 10.14.5

I am trying to use node-7z-forall, but when the module is installing I get this error:

Error: Error: Command failed: /Users/luisnomad/Projects/personal/7ztozip/node_modules/all-unpacker/unar "/Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/p7zip-16.02.pkg" -o /Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/darwin -f -D

    at /Users/luisnomad/Projects/personal/7ztozip/node_modules/all-unpacker/index.js:45:40
    at ChildProcess.exithandler (child_process.js:301:5)
    at ChildProcess.emit (events.js:189:13)
    at maybeClose (internal/child_process.js:970:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

I've tried running the failing command separately:

/Users/luisnomad/Projects/personal/7ztozip/node_modules/all-unpacker/unar "/Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/p7zip-16.02.pkg" -o /Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/darwin -f -D

the output is:

/Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/p7zip-16.02.pkg: [1] 14578 segmentation fault /Users/luisnomad/Projects/personal/7ztozip/node_modules/all-unpacker/unar -o

Since the binary is not successfully installed, I get this error when doing extractFull:

{ Error: spawn /Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/binaries/darwin/7za ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  errno: 'ENOENT',
  code: 'ENOENT',
  syscall:
   'spawn /Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/binaries/darwin/7za',
  path:
   '/Users/luisnomad/Projects/personal/7ztozip/node_modules/node-7z-forall/binaries/darwin/7za',
  spawnargs:
   [ 'x',
     '/Users/luisnomad/Projects/personal/7ztozip/AI Shougi 3.7z',
     '-o/Users/luisnomad/Projects/personal/7ztozip/temp',
     '-$bin/Users/luisnomad/Projects/personal/7ztozip/node_modules/7zip-bin/mac/7za',
     '-ssc',
     '-y',
     '-bb2' ] }

I have 7z installed on my machine but it doesn't seem to try using it.

Any ideas?

not able to get proper error in case of corrupted zip file

when i am using 7z as command for unzip file i am getting error message:

resident_image.png CRC Failed in encrypted file. Wrong password?,data.json

but using node-7z module, it is calling error catch with error undefined so and i got the zip extracted
so at run time its difficult to know extraction status.

i got zip extracted so it worked for me but with patch of error undefined

SyntaxError: Unexpected token ...

On my production system, I received the following error running v1.1.0 of node-7z:

SyntaxError: Unexpected token ...
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/node/silexport/node_modules/node-7z/src/main.js:4:15)

My package.json is the following:

{
    "name": "MyName",
    "description": "MyDescription",
    "version": "1.0.0",
    "author": "me",
    "contributors": [],
    "dependencies": {
        "body-parser": "^1.18.3",
        "express": "^4.16.4",
        "request": "^2.88.0",
        "iconv-lite": "^0.4.24",
        "formatcoords": "^1.1.3",
        "mkdirp": "^0.5.1",
        "nodemailer": "^5.1.1",
        "jimp": "^0.6.0",
        "json2csv": "^4.3.3",
        "@icetee/ftp": "^1.0.3",
        "multer": "^1.4.1",
        "csv-parse": "^3.1.3",
        "node-7z": "^1.1.0"
    },
    "repository": {
        "type": "git",
        "url": "https://github.com/me/myrepo.git"
    },
    "license": "ISC",
    "main": "index.js",
    "files": [
        "index.js",
        "lib"
    ]
}

Do you have any idea what's wrong?

Update: My specs:

mylinuxuser:# node --version
v6.16.0
mylinuxuser:# npm --version
3.10.10
mylinuxuser:# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:        16.04
Codename:       xenial

zip blob with password

Hi,
I'm working with Angular (typescript).
How I can create zip with password passing Blob object or string, using Seven.add?
const myStream = Seven.add('Files.7z', '*.txt', {
recursive: true
})

I don't want to use files on local paths

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.