|
| 1 | +'use strict'; |
| 2 | +constcommon=require('../common'); |
| 3 | +constassert=require('assert'); |
| 4 | +const{ Worker }=require('worker_threads'); |
| 5 | +const{ once }=require('events'); |
| 6 | +constfs=require('fs'); |
| 7 | + |
| 8 | +// All the tests here are run sequentially, to avoid accidentally opening an fd |
| 9 | +// which another part of the test expects to be closed. |
| 10 | + |
| 11 | +constpreamble=` |
| 12 | +const fs = require("fs"); |
| 13 | +const { parentPort } = require('worker_threads'); |
| 14 | +const __filename = ${JSON.stringify(__filename)}; |
| 15 | +process.on('warning', (warning) => parentPort.postMessage({ warning })); |
| 16 | +`; |
| 17 | + |
| 18 | +(async()=>{ |
| 19 | +// Consistency check: Without trackUnmanagedFds, FDs are *not* closed. |
| 20 | +{ |
| 21 | +constw=newWorker(`${preamble} |
| 22 | + parentPort.postMessage(fs.openSync(__filename)); |
| 23 | + `,{eval: true,trackUnmanagedFds: false}); |
| 24 | +const[[fd]]=awaitPromise.all([once(w,'message'),once(w,'exit')]); |
| 25 | +assert(fd>2); |
| 26 | +fs.fstatSync(fd);// Does not throw. |
| 27 | +fs.closeSync(fd); |
| 28 | +} |
| 29 | + |
| 30 | +// With trackUnmanagedFds, FDs are closed automatically. |
| 31 | +{ |
| 32 | +constw=newWorker(`${preamble} |
| 33 | + parentPort.postMessage(fs.openSync(__filename)); |
| 34 | + `,{eval: true,trackUnmanagedFds: true}); |
| 35 | +const[[fd]]=awaitPromise.all([once(w,'message'),once(w,'exit')]); |
| 36 | +assert(fd>2); |
| 37 | +assert.throws(()=>fs.fstatSync(fd),{code: 'EBADF'}); |
| 38 | +} |
| 39 | + |
| 40 | +// There is a warning when an fd is unexpectedly opened twice. |
| 41 | +{ |
| 42 | +constw=newWorker(`${preamble} |
| 43 | + parentPort.postMessage(fs.openSync(__filename)); |
| 44 | + parentPort.once('message', () => { |
| 45 | + const reopened = fs.openSync(__filename); |
| 46 | + fs.closeSync(reopened); |
| 47 | + }); |
| 48 | + `,{eval: true,trackUnmanagedFds: true}); |
| 49 | +const[fd]=awaitonce(w,'message'); |
| 50 | +fs.closeSync(fd); |
| 51 | +w.postMessage(''); |
| 52 | +const[{ warning }]=awaitonce(w,'message'); |
| 53 | +assert.match(warning.message, |
| 54 | +/Filedescriptor\d+openedinunmanagedmodetwice/); |
| 55 | +} |
| 56 | + |
| 57 | +// There is a warning when an fd is unexpectedly closed. |
| 58 | +{ |
| 59 | +constw=newWorker(`${preamble} |
| 60 | + parentPort.once('message', (fd) => { |
| 61 | + fs.closeSync(fd); |
| 62 | + }); |
| 63 | + `,{eval: true,trackUnmanagedFds: true}); |
| 64 | +w.postMessage(fs.openSync(__filename)); |
| 65 | +const[{ warning }]=awaitonce(w,'message'); |
| 66 | +assert.match(warning.message, |
| 67 | +/Filedescriptor\d+closedbutnotopenedinunmanagedmode/); |
| 68 | +} |
| 69 | +})().then(common.mustCall()); |
0 commit comments