module: simpler shebang function

This simplifies the shebang function significantly. Before, it was
optimized for two characters input. Any module actually parsed should
however have more characters than just the shebang.
The performance stays the same as before.

PR-URL: https://github.com/nodejs/node/pull/26266
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Ruben Bridgewater 2018-12-31 02:01:00 +01:00
parent 8347dbefc3
commit 3fce5cf439
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762

View File

@ -5,13 +5,6 @@ const path = require('path');
const { pathToFileURL } = require('internal/url'); const { pathToFileURL } = require('internal/url');
const { URL } = require('url'); const { URL } = require('url');
const {
CHAR_LINE_FEED,
CHAR_CARRIAGE_RETURN,
CHAR_EXCLAMATION_MARK,
CHAR_HASH,
} = require('internal/constants');
// Invoke with makeRequireFunction(module) where |module| is the Module object // Invoke with makeRequireFunction(module) where |module| is the Module object
// to use as the context for the require() function. // to use as the context for the require() function.
function makeRequireFunction(mod) { function makeRequireFunction(mod) {
@ -67,31 +60,17 @@ function stripBOM(content) {
*/ */
function stripShebang(content) { function stripShebang(content) {
// Remove shebang // Remove shebang
var contLen = content.length; if (content.charAt(0) === '#' && content.charAt(1) === '!') {
if (contLen >= 2) { // Find end of shebang line and slice it off
if (content.charCodeAt(0) === CHAR_HASH && let index = content.indexOf('\n', 2);
content.charCodeAt(1) === CHAR_EXCLAMATION_MARK) { if (index === -1)
if (contLen === 2) { return '';
// Exact match if (content.charAt(index - 1) === '\r')
content = ''; index--;
} else { // Note that this actually includes the newline character(s) in the
// Find end of shebang line and slice it off // new output. This duplicates the behavior of the regular expression
var i = 2; // that was previously used to replace the shebang line.
for (; i < contLen; ++i) { content = content.slice(index);
var code = content.charCodeAt(i);
if (code === CHAR_LINE_FEED || code === CHAR_CARRIAGE_RETURN)
break;
}
if (i === contLen)
content = '';
else {
// Note that this actually includes the newline character(s) in the
// new output. This duplicates the behavior of the regular expression
// that was previously used to replace the shebang line
content = content.slice(i);
}
}
}
} }
return content; return content;
} }