From 3fce5cf439cea1808e8984640638aac5c2b08b12 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 31 Dec 2018 02:01:00 +0100 Subject: [PATCH] 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 Reviewed-By: James M Snell --- lib/internal/modules/cjs/helpers.js | 43 ++++++++--------------------- 1 file changed, 11 insertions(+), 32 deletions(-) diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js index 2e5290b4520a27..874805beccd39c 100644 --- a/lib/internal/modules/cjs/helpers.js +++ b/lib/internal/modules/cjs/helpers.js @@ -5,13 +5,6 @@ const path = require('path'); const { pathToFileURL } = require('internal/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 // to use as the context for the require() function. function makeRequireFunction(mod) { @@ -67,31 +60,17 @@ function stripBOM(content) { */ function stripShebang(content) { // Remove shebang - var contLen = content.length; - if (contLen >= 2) { - if (content.charCodeAt(0) === CHAR_HASH && - content.charCodeAt(1) === CHAR_EXCLAMATION_MARK) { - if (contLen === 2) { - // Exact match - content = ''; - } else { - // Find end of shebang line and slice it off - var i = 2; - for (; i < contLen; ++i) { - 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); - } - } - } + if (content.charAt(0) === '#' && content.charAt(1) === '!') { + // Find end of shebang line and slice it off + let index = content.indexOf('\n', 2); + if (index === -1) + return ''; + if (content.charAt(index - 1) === '\r') + index--; + // 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(index); } return content; }