Skip to content
This repository has been archived by the owner on May 25, 2020. It is now read-only.

__dirname hack #25

Open
netsgnut opened this issue Jul 6, 2015 · 0 comments
Open

__dirname hack #25

netsgnut opened this issue Jul 6, 2015 · 0 comments

Comments

@netsgnut
Copy link

netsgnut commented Jul 6, 2015

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant