stephenmathieson / node-obfuscator

maintainer wanted → Obfuscate your node packages because your boss says so!
216 stars 36 forks source link

`__dirname` hack #25

Open netsgnut opened 9 years ago

netsgnut commented 9 years ago

It is not an issue, frankly, but more like some kind of notes in case if some others happen to stumble upon this humble note and, well, in need of something like this.

In my case, a project that "requires obfuscation" (well, talk about those cases), it has quite some lines of code that requires doing something on __dirname like path.resolve(__dirname, '..', 'package.json') or so. They won't work as they are concatenated, obviously, and placed at the root of the directory.

Therefore, I have hacked something like the following to "kind of" conserve the __dirname for the module within. It is a rough hack and works for me here, but I am pretty sure it is not for everyone.

obfuscator.register = function (root, file, cb) {
  var filename = dotslash(path.relative(root, file));

  fs.readFile(file, 'utf-8', function (err, data) {
    if (err) {
      return cb(err);
    }

    var code =
      'require.register("' + filename + '",' + 'function (module, exports, require) {' +
        'var ___dirname = __dirname + "/' + filename.substr(2, filename.lastIndexOf('/') - 2) + '";' +
        (rJSON.test(file)
          ? ('module.exports = ' + data + ';')
          : data.replace(/__dirname/g, '___dirname'))
      + '});';
    return cb(null, code);
  });
};

The __dirname gets uglified nicely so it would work within. Be noted that in my case I have only tested with cases where './' is the defacto root - it probably won't work if it is not the case.

Again it is a horrible, horrible, kind of hack. Not sure how useful it can be for any of you who are reading this, but, well, take it if you need something like that. YMMV, though.