Skip to content

Commit 2a66cd3

Browse files
BridgeARaddaleax
authored andcommitted
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: #26266 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 0c8e9ee commit 2a66cd3

File tree

1 file changed

+11
-32
lines changed

1 file changed

+11
-32
lines changed

lib/internal/modules/cjs/helpers.js

+11-32
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,6 @@ const path = require('path');
55
const { pathToFileURL } = require('internal/url');
66
const { URL } = require('url');
77

8-
const {
9-
CHAR_LINE_FEED,
10-
CHAR_CARRIAGE_RETURN,
11-
CHAR_EXCLAMATION_MARK,
12-
CHAR_HASH,
13-
} = require('internal/constants');
14-
158
// Invoke with makeRequireFunction(module) where |module| is the Module object
169
// to use as the context for the require() function.
1710
function makeRequireFunction(mod) {
@@ -67,31 +60,17 @@ function stripBOM(content) {
6760
*/
6861
function stripShebang(content) {
6962
// Remove shebang
70-
var contLen = content.length;
71-
if (contLen >= 2) {
72-
if (content.charCodeAt(0) === CHAR_HASH &&
73-
content.charCodeAt(1) === CHAR_EXCLAMATION_MARK) {
74-
if (contLen === 2) {
75-
// Exact match
76-
content = '';
77-
} else {
78-
// Find end of shebang line and slice it off
79-
var i = 2;
80-
for (; i < contLen; ++i) {
81-
var code = content.charCodeAt(i);
82-
if (code === CHAR_LINE_FEED || code === CHAR_CARRIAGE_RETURN)
83-
break;
84-
}
85-
if (i === contLen)
86-
content = '';
87-
else {
88-
// Note that this actually includes the newline character(s) in the
89-
// new output. This duplicates the behavior of the regular expression
90-
// that was previously used to replace the shebang line
91-
content = content.slice(i);
92-
}
93-
}
94-
}
63+
if (content.charAt(0) === '#' && content.charAt(1) === '!') {
64+
// Find end of shebang line and slice it off
65+
let index = content.indexOf('\n', 2);
66+
if (index === -1)
67+
return '';
68+
if (content.charAt(index - 1) === '\r')
69+
index--;
70+
// Note that this actually includes the newline character(s) in the
71+
// new output. This duplicates the behavior of the regular expression
72+
// that was previously used to replace the shebang line.
73+
content = content.slice(index);
9574
}
9675
return content;
9776
}

0 commit comments

Comments
 (0)