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 /* 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} 97