• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const fs = require('fs');
4const assert = require('assert');
5const path = require('path');
6const tmpdir = require('../common/tmpdir');
7const file = path.join(tmpdir.path, 'read_stream_filehandle_worker.txt');
8const input = 'hello world';
9const { Worker, isMainThread, workerData } = require('worker_threads');
10
11if (isMainThread || !workerData) {
12  tmpdir.refresh();
13  fs.writeFileSync(file, input);
14
15  fs.promises.open(file, 'r').then((handle) => {
16    handle.on('close', common.mustNotCall());
17    new Worker(__filename, {
18      workerData: { handle },
19      transferList: [handle]
20    });
21  });
22  fs.promises.open(file, 'r').then(async (handle) => {
23    try {
24      fs.createReadStream(null, { fd: handle });
25      assert.throws(() => {
26        new Worker(__filename, {
27          workerData: { handle },
28          transferList: [handle]
29        });
30      }, {
31        code: 25,
32        name: 'DataCloneError',
33      });
34    } finally {
35      await handle.close();
36    }
37  });
38} else {
39  let output = '';
40
41  const handle = workerData.handle;
42  handle.on('close', common.mustCall());
43  const stream = fs.createReadStream(null, { fd: handle });
44
45  stream.on('data', common.mustCallAtLeast((data) => {
46    output += data;
47  }));
48
49  stream.on('end', common.mustCall(() => {
50    handle.close();
51    assert.strictEqual(output, input);
52  }));
53
54  stream.on('close', common.mustCall());
55}
56