Skip to content
Permalink
Browse files

Dynamically calculate __dirname and __filename when --node is passed

When `--no-commondir` is set (as a consequence of `--node` for example),
it will cause the final bundle to hardcode absolute values of the
machine that generated the bundle in order to resolve `__dirname` and
`__filename`. For example, consider a `foo.js` file containing:

```js
console.log(__dirname);
console.log(__filename);
```

Calling `browserify --node` on it results in:

```js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (__filename,__dirname){
console.log(__dirname);
console.log(__filename);

}).call(this,"/Users/jviotti/Projects/playground/node-browserify/foo.js","/Users/jviotti/Projects/playground/node-browserify")
},{}]},{},[1]);
```

Notice the absolute paths at the end of the bundle. This means that
Browserify node users can't generate a bundle in one machine, and expect
it to run without issues on another machine.

As a solution, we can use the final bundle's `__dirname` to dynamically
resolve every file's `__dirname` and `__filename`. This change only
takes place when `--node` is set, and keeps Browserify backwards
compatible.

For example, the above output might contain the following line:

```
}).call(this,require("path").join(__dirname,"foo.js"),require("path").join(__dirname,"."))
```

Fixes: #1723
See: balena-io/etcher#1429
See: balena-io/etcher#1409
Signed-off-by: Juan Cruz Viotti <jviotti@openmailbox.org>
Signed-off-by: Juan Cruz Viotti <jv@jviotti.com>
  • Loading branch information...
Juan Cruz Viotti authored and jviotti committed May 17, 2017
1 parent 89809c3 commit 9306a57c027e0ea813b97e60ece27e232525dcbf
Showing with 103 additions and 6 deletions.
  1. +16 −2 index.js
  2. +77 −1 test/bare.js
  3. +4 −0 test/bare/dirname-filename.js
  4. +6 −3 test/no_builtins.js
@@ -1,3 +1,4 @@
var path = require('path');
var mdeps = require('module-deps');
var depsSort = require('deps-sort');
var bpack = require('browser-pack');
@@ -551,6 +552,19 @@ Browserify.prototype._createDeps = function (opts) {
return through();
}
}

if (opts.commondir === false && opts.builtins === false) {
opts.insertGlobalVars = xtend({
__dirname: function(file, basedir) {
var dir = path.dirname(path.relative(basedir, file));
return 'require("path").join(__dirname,' + dir.split(path.sep).map(JSON.stringify).join(',') + ')';
},
__filename: function(file, basedir) {
var filename = path.relative(basedir, file);
return 'require("path").join(__dirname,' + filename.split(path.sep).map(JSON.stringify).join(',') + ')';
}
}, opts.insertGlobalVars);
}

var vars = xtend({
process: function () { return "require('_process')" },
@@ -560,11 +574,11 @@ Browserify.prototype._createDeps = function (opts) {
vars.process = undefined;
vars.buffer = undefined;
}

return insertGlobals(file, xtend(opts, {
debug: opts.debug,
always: opts.insertGlobals,
basedir: opts.commondir === false
basedir: opts.commondir === false && isArray(opts.builtins)
? '/'
: opts.basedir || process.cwd()
,
@@ -3,6 +3,10 @@ var spawn = require('child_process').spawn;
var path = require('path');
var concat = require('concat-stream');
var vm = require('vm');
var fs = require('fs');
var temp = require('temp');
temp.track();
var tmpdir = temp.mkdirSync({prefix: 'browserify-test'});

test('bare', function (t) {
t.plan(4);
@@ -41,14 +45,17 @@ test('bare', function (t) {
test('bare inserts __filename,__dirname but not process,global,Buffer', function (t) {
t.plan(2);

var file = path.resolve(__dirname, 'bare/main.js');
var ps = spawn(process.execPath, [
path.resolve(__dirname, '../bin/cmd.js'),
path.resolve(__dirname, 'bare/main.js'),
file,
'--bare'
]);

ps.stdout.pipe(concat(function (body) {
vm.runInNewContext(body, {
require: require,
__dirname: process.cwd(),
console: {
log: function (msg) {
t.same(msg, [
@@ -68,3 +75,72 @@ test('bare inserts __filename,__dirname but not process,global,Buffer', function
t.equal(code, 0);
});
});

test('bare inserts dynamic __filename,__dirname', function (t) {
t.plan(2);

var file = path.join(tmpdir, 'dirname-filename.js');

fs.writeFileSync(
file,
fs.readFileSync(path.resolve(__dirname, 'bare/dirname-filename.js'))
);

var ps = spawn(process.execPath, [
path.resolve(__dirname, '../bin/cmd.js'),
file,
'--bare'
]);

ps.stdout.pipe(concat(function (body) {
vm.runInNewContext(body, {
require: require,
__dirname: path.dirname(file),
console: {
log: function (msg) {
t.same(msg, [
path.dirname(file),
file
]);
}
}
});
}));
ps.stdin.end();

ps.on('exit', function (code) {
t.equal(code, 0);
});
});

test('bare inserts dynamic __filename,__dirname with basedir', function (t) {
t.plan(2);

var file = 'dirname-filename.js';
var ps = spawn(process.execPath, [
path.resolve(__dirname, '../bin/cmd.js'),
file,
'--bare',
'--basedir=' + path.join(__dirname, 'bare')
]);

ps.stdout.pipe(concat(function (body) {
vm.runInNewContext(body, {
require: require,
__dirname: process.cwd(),
console: {
log: function (msg) {
t.same(msg, [
__dirname,
path.join(__dirname, file)
]);
}
}
});
}));
ps.stdin.end();

ps.on('exit', function (code) {
t.equal(code, 0);
});
});
@@ -0,0 +1,4 @@
console.log([
__dirname,
__filename
]);
@@ -1,12 +1,14 @@
var browserify = require('../');
var test = require('tap').test;
var path = require('path');
var vm = require('vm');

test('builtins false', function (t) {
t.plan(1);


var file = __dirname + '/no_builtins/main.js';
var b = browserify({
entries: [ __dirname + '/no_builtins/main.js' ],
entries: [ file ],
commondir: false,
builtins: false
});
@@ -15,7 +17,8 @@ test('builtins false', function (t) {
console: { log: function (msg) {
t.equal(msg, 'beep boop\n');
} },
require: require
require: require,
__dirname: process.cwd()
};
vm.runInNewContext(src, c);
});

0 comments on commit 9306a57

Please sign in to comment.
You can’t perform that action at this time.