|
1 | 1 | 'use strict';
|
2 |
| -require('../common'); |
| 2 | +const common = require('../common'); |
3 | 3 |
|
4 | 4 | // Test fs.readFile using a file descriptor.
|
5 | 5 |
|
6 | 6 | const fixtures = require('../common/fixtures');
|
7 | 7 | const assert = require('assert');
|
8 | 8 | const fs = require('fs');
|
9 | 9 | const fn = fixtures.path('empty.txt');
|
| 10 | +const join = require('path').join; |
| 11 | +const tmpdir = require('../common/tmpdir'); |
| 12 | +tmpdir.refresh(); |
10 | 13 |
|
11 | 14 | tempFd(function(fd, close) {
|
12 | 15 | fs.readFile(fd, function(err, data) {
|
@@ -46,3 +49,48 @@ function tempFdSync(callback) {
|
46 | 49 | callback(fd);
|
47 | 50 | fs.closeSync(fd);
|
48 | 51 | }
|
| 52 | + |
| 53 | +{ |
| 54 | + /* |
| 55 | + * This test makes sure that `readFile()` always reads from the current |
| 56 | + * position of the file, instead of reading from the beginning of the file, |
| 57 | + * when used with file descriptors. |
| 58 | + */ |
| 59 | + |
| 60 | + const filename = join(tmpdir.path, 'test.txt'); |
| 61 | + fs.writeFileSync(filename, 'Hello World'); |
| 62 | + |
| 63 | + { |
| 64 | + /* Tests the fs.readFileSync(). */ |
| 65 | + const fd = fs.openSync(filename, 'r'); |
| 66 | + |
| 67 | + /* Read only five bytes, so that the position moves to five. */ |
| 68 | + const buf = Buffer.alloc(5); |
| 69 | + assert.deepStrictEqual(fs.readSync(fd, buf, 0, 5), 5); |
| 70 | + assert.deepStrictEqual(buf.toString(), 'Hello'); |
| 71 | + |
| 72 | + /* readFileSync() should read from position five, instead of zero. */ |
| 73 | + assert.deepStrictEqual(fs.readFileSync(fd).toString(), ' World'); |
| 74 | + } |
| 75 | + |
| 76 | + { |
| 77 | + /* Tests the fs.readFile(). */ |
| 78 | + fs.open(filename, 'r', common.mustCall((err, fd) => { |
| 79 | + assert.ifError(err); |
| 80 | + const buf = Buffer.alloc(5); |
| 81 | + |
| 82 | + /* Read only five bytes, so that the position moves to five. */ |
| 83 | + fs.read(fd, buf, 0, 5, null, common.mustCall((err, bytes) => { |
| 84 | + assert.ifError(err); |
| 85 | + assert.strictEqual(bytes, 5); |
| 86 | + assert.deepStrictEqual(buf.toString(), 'Hello'); |
| 87 | + |
| 88 | + fs.readFile(fd, common.mustCall((err, data) => { |
| 89 | + assert.ifError(err); |
| 90 | + /* readFile() should read from position five, instead of zero. */ |
| 91 | + assert.deepStrictEqual(data.toString(), ' World'); |
| 92 | + })); |
| 93 | + })); |
| 94 | + })); |
| 95 | + } |
| 96 | +} |
0 commit comments