diff --git a/lib/path.js b/lib/path.js index b371f422b6b..0287e18c2e4 100644 --- a/lib/path.js +++ b/lib/path.js @@ -578,7 +578,7 @@ const win32 = { for (let i = 0; i < joined.length; i++) { if (joined[i] === '\\') { - if (part) parts.push(part); + if (part) parts[parts.length] = part; part = ''; // Skip consecutive backslashes while (i + 1 < joined.length && joined[i + 1] === '\\') i++; @@ -587,7 +587,7 @@ const win32 = { } } // Add the final part if any - if (part) parts.push(part); + if (part) parts[parts.length] = part; // Check if any part has a Windows reserved name if (parts.some((p) => { @@ -1344,7 +1344,7 @@ const posix = { const arg = args[i]; validateString(arg, 'path'); if (arg.length > 0) { - path.push(arg); + path[path.length] = arg; } } diff --git a/test/parallel/test-path-join-array-push.js b/test/parallel/test-path-join-array-push.js new file mode 100644 index 00000000000..5d4e3b4b61f --- /dev/null +++ b/test/parallel/test-path-join-array-push.js @@ -0,0 +1,28 @@ +'use strict'; + +// path.join() must not depend on a user-modified Array.prototype.push. + +require('../common'); +const assert = require('assert'); +const path = require('path'); + +const cases = [ + [path.posix, ['foo', '', 'bar', 'baz/'], 'foo/bar/baz/'], + [path.posix, ['/a', 'b', '../c'], '/a/c'], + [path.win32, ['foo', '', 'bar\\\\baz'], 'foo\\bar\\baz'], + [path.win32, ['C:\\a', 'b', '..\\c'], 'C:\\a\\c'], +]; + +for (const [{ join }, args, expected] of cases) { + const originalPush = Array.prototype.push; + let result; + Array.prototype.push = function() { + throw new Error('Array.prototype.push should not be called'); + }; + try { + result = join(...args); + } finally { + Array.prototype.push = originalPush; + } + assert.strictEqual(result, expected); +}