/
test-fs-writefile-with-fd.js
96 lines (78 loc) Β· 2.63 KB
/
test-fs-writefile-with-fd.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
// This test makes sure that `writeFile()` always writes from the current
// position of the file, instead of truncating the file, when used with file
// descriptors.
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const join = require('path').join;
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
{
/* writeFileSync() test. */
const filename = join(tmpdir.path, 'test.txt');
/* Open the file descriptor. */
const fd = fs.openSync(filename, 'w');
try {
/* Write only five characters, so that the position moves to five. */
assert.strictEqual(fs.writeSync(fd, 'Hello'), 5);
assert.strictEqual(fs.readFileSync(filename).toString(), 'Hello');
/* Write some more with writeFileSync(). */
fs.writeFileSync(fd, 'World');
/* New content should be written at position five, instead of zero. */
assert.strictEqual(fs.readFileSync(filename).toString(), 'HelloWorld');
} finally {
fs.closeSync(fd);
}
}
const fdsToCloseOnExit = [];
process.on('beforeExit', common.mustCall(() => {
for (const fd of fdsToCloseOnExit) {
try {
fs.closeSync(fd);
} catch {
// Failed to close, ignore
}
}
}));
{
/* writeFile() test. */
const file = join(tmpdir.path, 'test1.txt');
/* Open the file descriptor. */
fs.open(file, 'w', common.mustSucceed((fd) => {
fdsToCloseOnExit.push(fd);
/* Write only five characters, so that the position moves to five. */
fs.write(fd, 'Hello', common.mustSucceed((bytes) => {
assert.strictEqual(bytes, 5);
assert.strictEqual(fs.readFileSync(file).toString(), 'Hello');
/* Write some more with writeFile(). */
fs.writeFile(fd, 'World', common.mustSucceed(() => {
/* New content should be written at position five, instead of zero. */
assert.strictEqual(fs.readFileSync(file).toString(), 'HelloWorld');
}));
}));
}));
}
// Test read-only file descriptor
{
// TODO(pd4d10): https://github.com/nodejs/node/issues/38607
const expectedError = common.isWindows ? /EPERM/ : /EBADF/;
const file = join(tmpdir.path, 'test.txt');
fs.open(file, 'r', common.mustSucceed((fd) => {
fdsToCloseOnExit.push(fd);
fs.writeFile(fd, 'World', common.expectsError(expectedError));
}));
}
// Test with an AbortSignal
{
const controller = new AbortController();
const signal = controller.signal;
const file = join(tmpdir.path, 'test.txt');
fs.open(file, 'w', common.mustSucceed((fd) => {
fdsToCloseOnExit.push(fd);
fs.writeFile(fd, 'World', { signal }, common.expectsError({
name: 'AbortError'
}));
}));
controller.abort();
}