Skip to content

Commit

Permalink
Dynamically calculate __dirname and __filename when --node is passed
Browse files Browse the repository at this point in the history
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 Dec 25, 2017
1 parent 89809c3 commit 9306a57
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 6 deletions.
18 changes: 16 additions & 2 deletions index.js
@@ -1,3 +1,4 @@
var path = require('path');
var mdeps = require('module-deps');
var depsSort = require('deps-sort');
var bpack = require('browser-pack');
Expand Down Expand Up @@ -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')" },
Expand All @@ -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()
,
Expand Down
78 changes: 77 additions & 1 deletion test/bare.js
Expand Up @@ -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);
Expand Down Expand Up @@ -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, [
Expand All @@ -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);
});
});
4 changes: 4 additions & 0 deletions test/bare/dirname-filename.js
@@ -0,0 +1,4 @@
console.log([
__dirname,
__filename
]);
9 changes: 6 additions & 3 deletions test/no_builtins.js
@@ -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
});
Expand All @@ -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);
});
Expand Down

0 comments on commit 9306a57

Please sign in to comment.