Skip to content

Commit 177ec0d

Browse files
committed
os: fix tmpdir() returning 'undefined\temp' on Windows
When process.env is cleared (e.g., in sandboxed environments), os.tmpdir() would return 'undefined\temp' on Windows due to string concatenation with undefined values. This fix: - Checks for valid environment variables before using them - Falls back to getTempDir() when env vars are unavailable - Adds test case to prevent regression Reported-by: @rhysd Fixes: #60582 @ry Could you please review this fix?
1 parent f4145f0 commit 177ec0d

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

lib/os.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -179,15 +179,24 @@ platform[SymbolToPrimitive] = () => process.platform;
179179
*/
180180
function tmpdir() {
181181
if (isWindows) {
182-
const path = process.env.TEMP ||
183-
process.env.TMP ||
184-
(process.env.SystemRoot || process.env.windir) + '\\temp';
182+
const temp = process.env.TEMP || process.env.TMP;
183+
if (temp) {
184+
if (temp.length > 1 && temp[temp.length - 1] === '\\' && temp[temp.length - 2] !== ':') {
185+
return StringPrototypeSlice(temp, 0, -1);
186+
}
187+
return temp;
188+
}
185189

186-
if (path.length > 1 && path[path.length - 1] === '\\' && path[path.length - 2] !== ':') {
187-
return StringPrototypeSlice(path, 0, -1);
190+
const systemRoot = process.env.SystemRoot || process.env.windir;
191+
if (systemRoot) {
192+
const path = systemRoot + '\\temp';
193+
if (path.length > 1 && path[path.length - 1] === '\\' && path[path.length - 2] !== ':') {
194+
return StringPrototypeSlice(path, 0, -1);
195+
}
196+
return path;
188197
}
189198

190-
return path;
199+
return getTempDir() || 'C:\\temp';
191200
}
192201

193202
return getTempDir() || '/tmp';

test/parallel/test-os.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ if (common.isWindows) {
5757
assert.strictEqual(os.tmpdir(), '\\');
5858
process.env.TEMP = 'C:\\';
5959
assert.strictEqual(os.tmpdir(), 'C:\\');
60+
61+
// Test case for issue #60582: tmpdir() should not return 'undefined\temp'
62+
// when all environment variables are cleared
63+
const originalEnv = { ...process.env };
64+
process.env = {};
65+
const result = os.tmpdir();
66+
assert.ok(!result.includes('undefined'),
67+
`tmpdir() should not contain 'undefined', got: ${result}`);
68+
process.env = originalEnv;
6069
} else {
6170
assert.strictEqual(os.tmpdir(), '/tmpdir');
6271
process.env.TMPDIR = '';

0 commit comments

Comments
 (0)