1'use strict';
2const common = require('../common');
3
4// Test fs.readFile using a file descriptor.
5
6const fixtures = require('../common/fixtures');
7const assert = require('assert');
8const fs = require('fs');
9const fn = fixtures.path('empty.txt');
10const join = require('path').join;
11const tmpdir = require('../common/tmpdir');
12tmpdir.refresh();
13
14tempFd(function(fd, close) {
15  fs.readFile(fd, function(err, data) {
16    assert.ok(data);
17    close();
18  });
19});
20
21tempFd(function(fd, close) {
22  fs.readFile(fd, 'utf8', function(err, data) {
23    assert.strictEqual(data, '');
24    close();
25  });
26});
27
28tempFdSync(function(fd) {
29  assert.ok(fs.readFileSync(fd));
30});
31
32tempFdSync(function(fd) {
33  assert.strictEqual(fs.readFileSync(fd, 'utf8'), '');
34});
35
36function tempFd(callback) {
37  fs.open(fn, 'r', function(err, fd) {
38    assert.ifError(err);
39    callback(fd, function() {
40      fs.close(fd, function(err) {
41        assert.ifError(err);
42      });
43    });
44  });
45}
46
47function tempFdSync(callback) {
48  const fd = fs.openSync(fn, 'r');
49  callback(fd);
50  fs.closeSync(fd);
51}
52
53{
54  // This test makes sure that `readFile()` always reads from the current
55  // position of the file, instead of reading from the beginning of the file,
56  // when used with file descriptors.
57
58  const filename = join(tmpdir.path, 'test.txt');
59  fs.writeFileSync(filename, 'Hello World');
60
61  {
62    // Tests the fs.readFileSync().
63    const fd = fs.openSync(filename, 'r');
64
65    // Read only five bytes, so that the position moves to five.
66    const buf = Buffer.alloc(5);
67    assert.strictEqual(fs.readSync(fd, buf, 0, 5), 5);
68    assert.strictEqual(buf.toString(), 'Hello');
69
70    // readFileSync() should read from position five, instead of zero.
71    assert.strictEqual(fs.readFileSync(fd).toString(), ' World');
72
73    fs.closeSync(fd);
74  }
75
76  {
77    // Tests the fs.readFile().
78    fs.open(filename, 'r', common.mustSucceed((fd) => {
79      const buf = Buffer.alloc(5);
80
81      // Read only five bytes, so that the position moves to five.
82      fs.read(fd, buf, 0, 5, null, common.mustSucceed((bytes) => {
83        assert.strictEqual(bytes, 5);
84        assert.strictEqual(buf.toString(), 'Hello');
85
86        fs.readFile(fd, common.mustSucceed((data) => {
87          // readFile() should read from position five, instead of zero.
88          assert.strictEqual(data.toString(), ' World');
89
90          fs.closeSync(fd);
91        }));
92      }));
93    }));
94  }
95}
96