Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Commit 24d4539

Browse files
committed
module: strip byte order marker when loading *.js and *.json files
BOMs make V8 raise a 'SyntaxError: Unexpected token ILLEGAL' exception. Fixes #1440.
1 parent 48dcb90 commit 24d4539

File tree

4 files changed

+27
-8
lines changed

4 files changed

+27
-8
lines changed

lib/module.js

+20-8
Original file line numberDiff line numberDiff line change
@@ -416,23 +416,35 @@ Module.prototype._compile = function(content, filename) {
416416
return compiledWrapper.apply(self.exports, args);
417417
};
418418

419+
420+
function stripBOM(content) {
421+
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
422+
// because the buffer-to-string conversion in `fs.readFileSync()`
423+
// translates it to FEFF, the UTF-16 BOM.
424+
if (content.charCodeAt(0) === 0xFEFF) {
425+
content = content.slice(1);
426+
}
427+
return content;
428+
}
429+
430+
419431
// Native extension for .js
420432
Module._extensions['.js'] = function(module, filename) {
421433
var content = NativeModule.require('fs').readFileSync(filename, 'utf8');
422-
module._compile(content, filename);
423-
};
424-
425-
426-
// Native extension for .node
427-
Module._extensions['.node'] = function(module, filename) {
428-
process.dlopen(filename, module.exports);
434+
module._compile(stripBOM(content), filename);
429435
};
430436

431437

432438
// Native extension for .json
433439
Module._extensions['.json'] = function (module, filename) {
434440
var content = NativeModule.require('fs').readFileSync(filename, 'utf8');
435-
module.exports = JSON.parse(content);
441+
module.exports = JSON.parse(stripBOM(content));
442+
};
443+
444+
445+
//Native extension for .node
446+
Module._extensions['.node'] = function(module, filename) {
447+
process.dlopen(filename, module.exports);
436448
};
437449

438450

test/fixtures/utf8-bom.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = 42;

test/fixtures/utf8-bom.json

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
42

test/simple/test-module-loading.js

+5
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,8 @@ process.addListener('exit', function() {
221221

222222
console.log('exit');
223223
});
224+
225+
226+
// #1440 Loading files with a byte order marker.
227+
assert.equal(42, require('../fixtures/utf8-bom.js'));
228+
assert.equal(42, require('../fixtures/utf8-bom.json'));

0 commit comments

Comments
 (0)