Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lzma-native

Package Overview
Dependencies
Maintainers
1
Versions
92
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lzma-native

Provides bindings to the native liblzma library (.xz file format, among others)

  • 1.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
73K
increased by3.43%
Maintainers
1
Weekly downloads
 
Created
Source

lzma-native

NPM Version NPM Downloads Build Status Windows Coverage Status Dependency Status devDependency Status

Node.js interface to the native liblzma compression library (.xz file format, among others)

This package provides interfaces for compression and decompression of .xz (and legacy .lzma) files, both stream-based and string-based.

Example usage

Installation

Simply install lzma-native via npm:

$ npm install --save lzma-native

Note: As of version 1.0.0, this module provides pre-built binaries for multiple Node.js versions and all major OS using node-pre-gyp, so for 99 % of users no compiler toolchain is necessary. Please create an issue here if you have any trouble installing this module.

For streams

If you don’t have any fancy requirements, using this library is quite simple:

var lzma = require('lzma-native');

var compressor = lzma.createCompressor();
var input = fs.createReadStream('README.md');
var output = fs.createWriteStream('README.md.xz');

input.pipe(compressor).pipe(output);

For decompression, you can simply use lzma.createDecompressor().

Both functions return a stream where you can pipe your input in and read your (de)compressed output from.

For simple strings/Buffers

If you want your input/output to be Buffers (strings will be accepted as input), this even gets a little simpler:

lzma.compress('Banana', function(result) {
    console.log(result); // <Buffer fd 37 7a 58 5a 00 00 01 69 22 de 36 02 00 21 ...>
});

Again, replace lzma.compress with lzma.decompress and you’ll get the inverse transformation.

For node >= 0.12 (with Promise available), lzma.compress and lzma.decompress will return promises and you don’t need to provide any kind of callback (Example code).

API

Compatibility implementations

Apart from the API described here, lzma-native implements the APIs of the following other LZMA libraries so you can use it nearly as a drop-in replacement:

  • node-xz via lzma.Compressor and lzma.Decompressor
  • LZMA-JS via lzma.LZMA().compress and lzma.LZMA().decompress, though without actual support for progress functions and returning Buffer objects instead of integer arrays. (This produces output in the .lzma file format, not the .xz format!)

Reference

Encoding strings and Buffer objects

Creating streams for encoding

Functions

Internals

Encoding strings and Buffer objects

lzma.compress(), lzma.decompress()

lzma.compress(string, [opt, ]on_finish) lzma.decompress(string, [opt, ]on_finish)

ParamTypeDescription
stringBuffer / StringAny string or buffer to be (de)compressed (that can be passed to stream.end(…))
[opt]Options / intOptional. See options
on_finishCallbackWill be invoked with the resulting Buffer as the first parameter when encoding is finished, and as on_finish(null, err) in case of an error.

If promises are available, a promise will be returned.

Example code:

lzma.compress('Bananas', 9, function(result) {
    lzma.decompress(result, function(decompressedResult) {
        assert.equal(decompressedResult.toString(), 'Bananas');
    });
});

Example code for promises:

lzma.compress('Bananas', 9).then(function(result) {
    return lzma.decompress(result);
}).then(function(decompressedResult) {
    assert.equal(decompressedResult.toString(), 'Bananas');
}).catch(function(err) {
    // ...
});

lzma.LZMA().compress(), lzma.LZMA().decompress()

lzma.LZMA().compress(string, mode, on_finish[, on_progress]) lzma.LZMA().decompress(string, on_finish[, on_progress])

(Compatibility; See LZMA-JS for the original specs.)

Note that the result of compression is in the older LZMA1 format (.lzma files). This is different from the more universally used LZMA2 format (.xz files) and you will have to take care of possible compatibility issues with systems expecting .xz files.

ParamTypeDescription
stringBuffer / String / ArrayAny string, buffer, or array of integers or typed integers (e.g. Uint8Array)
modeintA number between 0 and 9, indicating compression level
on_finishCallbackWill be invoked with the resulting Buffer as the first parameter when encoding is finished, and as on_finish(null, err) in case of an error.
on_progressCallbackIndicates progress by passing a number in [0.0, 1.0]. Currently, this package only invokes the callback with 0.0 and 1.0.

If promises are available, a promise will be returned.

This does not work exactly as described in the original LZMA-JS specification:

  • The results are Buffer objects, not integer arrays. This just makes a lot more sense in a Node.js environment.
  • on_progress is currently only called with 0.0 and 1.0.

Example code:

lzma.LZMA().compress('Bananas', 4, function(result) {
    lzma.LZMA().decompress(result, function(decompressedResult) {
        assert.equal(decompressedResult.toString(), 'Bananas');
    });
});

For an example using promises, see compress().

Creating streams for encoding

lzma.createCompressor(), lzma.createDecompressor()

lzma.createCompressor([options]) lzma.createDecompressor([options])

ParamTypeDescription
[options]Options / intOptional. See options

Return a duplex stream, i.e. a both readable and writable stream. Input will be read, (de)compressed and written out. You can use this to pipe input through this stream, i.e. to mimick the xz command line util, you can write:

var compressor = lzma.createCompressor();

process.stdin.pipe(compressor).pipe(process.stdout);

The output of compression will be in LZMA2 format (.xz files), while decompression will accept either format via automatic detection.

lzma.Compressor(), lzma.Decompressor()

lzma.Compressor([preset], [options]) lzma.Decompressor([options])

(Compatibility; See node-xz for the original specs.)

These methods handle the .xz file format.

ParamTypeDescription
[preset]intOptional. See options.preset
[options]OptionsOptional. See options

Return a duplex stream, i.e. a both readable and writable stream. Input will be read, (de)compressed and written out. You can use this to pipe input through this stream, i.e. to mimick the xz command line util, you can write:

var compressor = lzma.Compressor();

process.stdin.pipe(compressor).pipe(process.stdout);

lzma.createStream()

lzma.createStream(coder, options)

ParamTypeDescription
[coder]stringAny of the supported coder names, e.g. "easyEncoder" (default) or "autoDecoder".
[options]Options / intOptional. See options

Return a duplex stream for (de-)compression. You can use this to pipe input through this stream.

The available coders are (the most interesting ones first):

Less likely to be of interest to you, but also available:

  • aloneDecoder Decoder which only uses the legacy .lzma format. Supports the options.memlimit option.
  • rawEncoder Custom encoder corresponding to lzma_raw_encoder (See the native library docs for details). Supports the options.filters option.
  • rawDecoder Custom decoder corresponding to lzma_raw_decoder (See the native library docs for details). Supports the options.filters option.
  • streamEncoder Custom encoder corresponding to lzma_stream_encoder (See the native library docs for details). Supports options.filters and options.check options.
  • streamDecoder Custom decoder corresponding to lzma_stream_decoder (See the native library docs for details). Supports options.memlimit and options.flags options.

Options

Option nameTypeDescription
checkcheckAny of lzma.CHECK_CRC32, lzma.CHECK_CRC64, lzma.CHECK_NONE, lzma.CHECK_SHA256
memlimitfloatA memory limit for (de-)compression in bytes
presetintA number from 0 to 9, 0 being the fastest and weakest compression, 9 the slowest and highest compression level. (Please also see the xz(1) manpage for notes – don’t just blindly use 9!) You can also OR this with lzma.PRESET_EXTREME (the -e option to the xz command line utility).
flagsintA bitwise or of lzma.LZMA_TELL_NO_CHECK, lzma.LZMA_TELL_UNSUPPORTED_CHECK, lzma.LZMA_TELL_ANY_CHECK, lzma.LZMA_CONCATENATED
synchronousboolIf true, forces synchronous coding (i.e. no usage of threading)
bufsizeintThe default size for allocated buffers

options.filters can, if the coder supports it, be an array of filter objects, each with the following properties:

  • .id Any of lzma.FILTERS_MAX, lzma.FILTER_ARM, lzma.FILTER_ARMTHUMB, lzma.FILTER_IA64, lzma.FILTER_POWERPC, lzma.FILTER_SPARC, lzma.FILTER_X86 or lzma.FILTER_DELTA, lzma.FILTER_LZMA1, lzma.FILTER_LZMA2

The delta filter supports the additional option .dist for a distance between bytes (see the xz(1) manpage).

The LZMA filter supports the additional options .dict_size, .lp, .lc, pb, .mode, nice_len, .mf, .depth and .preset. See the xz(1) manpage for meaning of these parameters and additional information.

Functions

lzma.isXZ()

lzma.isXZ(input)

Tells whether an input buffer is an XZ file (.xz, LZMA2 format) using the file format’s magic number. This is not a complete test, i.e. the data following the file header may still be invalid in some way.

ParamTypeDescription
inputstring / BufferAny string or Buffer (integer arrays accepted).

Example usage:

lzma.isXZ(fs.readFileSync('test/hamlet.txt.xz')); // => true
lzma.isXZ(fs.readFileSync('test/hamlet.txt.lzma')); // => false
lzma.isXZ('Banana'); // => false

(The magic number of XZ files is hex fd 37 7a 58 5a 00 at position 0.)

lzma.crc32()

lzma.crc32(input[, encoding[, previous]])

Compute the CRC32 checksum of a Buffer or string.

ParamTypeDescription
inputstring / BufferAny string or Buffer.
[encoding]stringOptional. If input is a string, an encoding to use when converting into binary.
[previous]intThe result of a previous CRC32 calculation so that you can compute the checksum per each chunk

Example usage:

lzma.crc32('Banana') // => 69690105

lzma.checkSize()

lzma.checkSize(check)

Return the byte size of a check sum.

ParamTypeDescription
checkcheckAny supported check constant.

Example usage:

lzma.checkSize(lzma.CHECK_SHA256) // => 16
lzma.checkSize(lzma.CHECK_CRC32)  // => 4

lzma.easyDecoderMemusage()

lzma.easyDecoderMemusage(preset)

Returns the approximate memory usage when decoding using easyDecoder for a given preset.

ParamTypeDescription
presetpresetA compression level from 0 to 9

Example usage:

lzma.easyDecoderMemusage(6) // => 8454192

lzma.easyEncoderMemusage()

lzma.easyEncoderMemusage(preset)

Returns the approximate memory usage when encoding using easyEncoder for a given preset.

ParamTypeDescription
presetpresetA compression level from 0 to 9

Example usage:

lzma.easyEncoderMemusage(6) // => 97620499

lzma.rawDecoderMemusage()

lzma.rawDecoderMemusage(filters)

Returns the approximate memory usage when decoding using rawDecoder for a given filter list.

ParamTypeDescription
filtersarrayAn array of filters

lzma.rawEncoderMemusage()

lzma.rawEncoderMemusage(filters)

Returns the approximate memory usage when encoding using rawEncoder for a given filter list.

ParamTypeDescription
filtersarrayAn array of filters

lzma.versionString()

lzma.versionString()

Returns the version of the underlying C library.

Example usage:

lzma.versionString() // => '5.2.1'

lzma.versionNumber()

lzma.versionNumber()

Returns the version of the underlying C library.

Example usage:

lzma.versionNumber() // => 50020012

Internals

lzma.setPromiseAPI()

lzma.setPromiseAPI([api])

Set the used Promise API for the methods that encode/decode single strings of buffers in one run. You can pass in null to remove promise support and 'default' to reset everything to auto-detection using any-promise.

The previous value will be returned; Passing no parameters will result in no change, i.e. can be used to test for availability of promises.

Example usage:

lzma.setPromiseAPI() // => [Function: Promise] or similar

var Q = require('q');
lzma.setPromiseAPI(Q); // => old value, e.g. [Function: Promise]
lzma.setPromiseAPI(); // => Q
lzma.setPromiseAPI(null); // disable promises, return Q again
lzma.setPromiseAPI('default'); // back to square 1

Note: This module uses the ES6 Promise API by default, which can be found in all Node.js versions >= 0.12. If no global Promise object is detected, but Q is somewhere in your node_modules, it will be used; Otherwise, promises are not available by default.

Installation

This package includes the native C library, so there is no need to install it separately.

Licensing

The original C library package contains code under various licenses, with its core (liblzma) being public domain. See its contents for details. This wrapper is licensed under the LGPL 3 or any later version of the LGPL.

Other implementations of the LZMA algorithms for node.js and/or web clients include:

Note that LZMA has been designed to have much faster decompression than compression, which is something you may want to take into account when choosing an compression algorithm for large files. Almost always, LZMA achieves higher compression ratios than other algorithms, though.

Acknowledgements

Initial development of this project was financially supported by Tradity.

Keywords

FAQs

Package last updated on 13 Feb 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc