1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const { Worker, isMainThread, parentPort } = require('worker_threads'); 5 6// Verify that cwd changes from the main thread are handled correctly in 7// workers. 8 9// Do not use isMainThread directly, otherwise the test would time out in case 10// it's started inside of another worker thread. 11if (!process.env.HAS_STARTED_WORKER) { 12 process.env.HAS_STARTED_WORKER = '1'; 13 if (!isMainThread) { 14 common.skip('This test can only run as main thread'); 15 } 16 // Normalize the current working dir to also work with the root folder. 17 process.chdir(__dirname); 18 19 assert(!process.cwd.toString().includes('Atomics.load')); 20 21 // 1. Start the first worker. 22 const w = new Worker(__filename); 23 w.once('message', common.mustCall((message) => { 24 // 5. Change the cwd and send that to the spawned worker. 25 assert.strictEqual(message, process.cwd()); 26 process.chdir('..'); 27 w.postMessage(process.cwd()); 28 })); 29} else if (!process.env.SECOND_WORKER) { 30 process.env.SECOND_WORKER = '1'; 31 32 // 2. Save the current cwd and verify that `process.cwd` includes the 33 // Atomics.load call and spawn a new worker. 34 const cwd = process.cwd(); 35 assert(process.cwd.toString().includes('Atomics.load')); 36 37 const w = new Worker(__filename); 38 w.once('message', common.mustCall((message) => { 39 // 4. Verify at the current cwd is identical to the received and the 40 // original one. 41 assert.strictEqual(process.cwd(), message); 42 assert.strictEqual(message, cwd); 43 parentPort.postMessage(cwd); 44 })); 45 46 parentPort.once('message', common.mustCall((message) => { 47 // 6. Verify that the current cwd is identical to the received one but not 48 // with the original one. 49 assert.strictEqual(process.cwd(), message); 50 assert.notStrictEqual(message, cwd); 51 w.postMessage(message); 52 })); 53} else { 54 // 3. Save the current cwd, post back to the "main" thread and verify that 55 // `process.cwd` includes the Atomics.load call. 56 const cwd = process.cwd(); 57 // Send the current cwd to the parent. 58 parentPort.postMessage(cwd); 59 assert(process.cwd.toString().includes('Atomics.load')); 60 61 parentPort.once('message', common.mustCall((message) => { 62 // 7. Verify that the current cwd is identical to the received one but 63 // not with the original one. 64 assert.strictEqual(process.cwd(), message); 65 assert.notStrictEqual(message, cwd); 66 })); 67} 68