mirror of
https://github.com/nodejs/node.git
synced 2024-11-21 10:59:27 +00:00
module: strip byte order marker when loading *.js and *.json files
BOMs make V8 raise a 'SyntaxError: Unexpected token ILLEGAL' exception. Fixes #1440.
This commit is contained in:
parent
f9cfd70946
commit
ac722bbed6
@ -416,23 +416,35 @@ Module.prototype._compile = function(content, filename) {
|
||||
return compiledWrapper.apply(self.exports, args);
|
||||
};
|
||||
|
||||
|
||||
function stripBOM(content) {
|
||||
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
|
||||
// because the buffer-to-string conversion in `fs.readFileSync()`
|
||||
// translates it to FEFF, the UTF-16 BOM.
|
||||
if (content.charCodeAt(0) === 0xFEFF) {
|
||||
content = content.slice(1);
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
|
||||
// Native extension for .js
|
||||
Module._extensions['.js'] = function(module, filename) {
|
||||
var content = NativeModule.require('fs').readFileSync(filename, 'utf8');
|
||||
module._compile(content, filename);
|
||||
};
|
||||
|
||||
|
||||
// Native extension for .node
|
||||
Module._extensions['.node'] = function(module, filename) {
|
||||
process.dlopen(filename, module.exports);
|
||||
module._compile(stripBOM(content), filename);
|
||||
};
|
||||
|
||||
|
||||
// Native extension for .json
|
||||
Module._extensions['.json'] = function (module, filename) {
|
||||
var content = NativeModule.require('fs').readFileSync(filename, 'utf8');
|
||||
module.exports = JSON.parse(content);
|
||||
module.exports = JSON.parse(stripBOM(content));
|
||||
};
|
||||
|
||||
|
||||
//Native extension for .node
|
||||
Module._extensions['.node'] = function(module, filename) {
|
||||
process.dlopen(filename, module.exports);
|
||||
};
|
||||
|
||||
|
||||
|
1
test/fixtures/utf8-bom.js
vendored
Normal file
1
test/fixtures/utf8-bom.js
vendored
Normal file
@ -0,0 +1 @@
|
||||
module.exports = 42;
|
1
test/fixtures/utf8-bom.json
vendored
Normal file
1
test/fixtures/utf8-bom.json
vendored
Normal file
@ -0,0 +1 @@
|
||||
42
|
@ -221,3 +221,8 @@ process.addListener('exit', function() {
|
||||
|
||||
console.log('exit');
|
||||
});
|
||||
|
||||
|
||||
// #1440 Loading files with a byte order marker.
|
||||
assert.equal(42, require('../fixtures/utf8-bom.js'));
|
||||
assert.equal(42, require('../fixtures/utf8-bom.json'));
|
||||
|
Loading…
Reference in New Issue
Block a user