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_test.txt');
8const input = 'hello world';
9
10tmpdir.refresh();
11fs.writeFileSync(file, input);
12
13fs.promises.open(file, 'r').then((handle) => {
14  handle.on('close', common.mustCall());
15  const stream = fs.createReadStream(null, { fd: handle });
16
17  let output = '';
18  stream.on('data', common.mustCallAtLeast((data) => {
19    output += data;
20  }));
21
22  stream.on('end', common.mustCall(() => {
23    assert.strictEqual(output, input);
24  }));
25
26  stream.on('close', common.mustCall());
27}).then(common.mustCall());
28
29fs.promises.open(file, 'r').then((handle) => {
30  handle.on('close', common.mustCall());
31  const stream = fs.createReadStream(null, { fd: handle });
32  stream.on('data', common.mustNotCall());
33  stream.on('close', common.mustCall());
34
35  return handle.close();
36}).then(common.mustCall());
37
38fs.promises.open(file, 'r').then((handle) => {
39  handle.on('close', common.mustCall());
40  const stream = fs.createReadStream(null, { fd: handle });
41  stream.on('close', common.mustCall());
42
43  stream.on('data', common.mustCall(() => {
44    handle.close();
45  }));
46}).then(common.mustCall());
47
48fs.promises.open(file, 'r').then((handle) => {
49  handle.on('close', common.mustCall());
50  const stream = fs.createReadStream(null, { fd: handle });
51  stream.on('close', common.mustCall());
52
53  stream.close();
54}).then(common.mustCall());
55
56fs.promises.open(file, 'r').then((handle) => {
57  assert.throws(() => {
58    fs.createReadStream(null, { fd: handle, fs });
59  }, {
60    code: 'ERR_METHOD_NOT_IMPLEMENTED',
61    name: 'Error',
62    message: 'The FileHandle with fs method is not implemented'
63  });
64  return handle.close();
65}).then(common.mustCall());
66
67fs.promises.open(file, 'r').then((handle) => {
68  const { read: originalReadFunction } = handle;
69  handle.read = common.mustCallAtLeast(function read() {
70    return Reflect.apply(originalReadFunction, this, arguments);
71  });
72
73  const stream = fs.createReadStream(null, { fd: handle });
74
75  let output = '';
76  stream.on('data', common.mustCallAtLeast((data) => {
77    output += data;
78  }));
79
80  stream.on('end', common.mustCall(() => {
81    assert.strictEqual(output, input);
82  }));
83}).then(common.mustCall());
84