V
V
vladymyr_olegovich2016-05-04 02:37:10
JavaScript
vladymyr_olegovich, 2016-05-04 02:37:10

How to get json data from archive in Node.js?

There is a "lib.txt" file. It is located in the "lib.txt.gz" archive.
This file contains a regular json object, like this:

var a = [
{a:1},
{b:2}
]

How can I get the array "a" in the server file itself using the "zlib" module?
I'm not very familiar with nodejs :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-05-04
@vladymyr_olegovich

const zlib = require('zlib');
const fs = require('fs');

/**
 * Read the gz compresed file
 * @param filename (string) full path to file
 * @return (Promise<Buffer>)
 */
function readGZipFile(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, (err, buf) => {
            if(err) {
                reject(err);
                return;
            }
            zlib.gunzip(buf, (err, buf) => {
                if(err) {
                    reject(err);
                    return;
                }
                resolve(buf);
            });
        });
    });
}

//Использование
const path = require('path');
readGZipFile(path.resolve(__dirname, 'lib.txt.gz')).then(buf => JSON.parse(buf.toString())).then(data => {
    //Ваш код для работы с data
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question