iwek iwek - 2 months ago 18
Node.js Question

How to require or evaluate gzipped JavaScript file with Node.js and zlib?


Everything works when I require a normal JavaScript file in Node:


var test = require('test.js');
console.log(test.foo); // prints the function


But now I have compressed that
test.js
file, reading it as a
string
works:

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

var gunzip = zlib.createGunzip();

var buffer = [];
fs.createReadStream('test.js.gz').pipe(gunzip);
gunzip.on('data', function(data){
buffer.push(data.toString())
});
gunzip.on('finish', function(){
console.log(buffer.join("")); //prints the JS file as string
}).on("error", function(e) {
console.log(e);
});


But, I don't want a
string
. Using
eval
does not seem right.

How can I evaluate the
string
as a JavaScript similar to what I get with require('test.js'); (I cannot use external libraries)

Answer

Here's a possible implementation:

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

function requireGZ(filename) {
  let code = zlib.gunzipSync(fs.readFileSync(filename)).toString();
  let mod  = new Module();

  mod._compile(code, filename);

  return mod.exports;
}

// Use:
let test = requireGZ('./test.js.gz');
Comments