@zenfs/devel 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ const cli = new Command('node-compat')
18
18
  .option('--ref <ref>', 'Ref to read from (default: upstream of main, or HEAD)')
19
19
  .option('--state <file>', 'Marks file', core.defaultMarksPath)
20
20
  .addHelpText('after', `\nThe first clone used is saved to ${displayPath(configPath)}.`);
21
- const sinceOption = new Option('--since <version>', 'Released in this version or later, or unreleased').default('18');
21
+ const sinceOption = new Option('--since <version>', 'Released in this version or later, or unreleased').default('4');
22
22
  /**
23
23
  * Loads the Node.js clone and marks, saving the clone if it is the first one used.
24
24
  */
@@ -64,7 +64,7 @@ cli.command('summary', { isDefault: true })
64
64
  console.log(styleText('bold', 'Node.js'.padEnd(9)), `${displayPath(node.path)} @ ${node.ref}`, styleText('dim', repoInfo));
65
65
  console.log(styleText('bold', 'ZenFS'.padEnd(9)), core.zenfs.version);
66
66
  console.log(styleText('bold', 'Marks'.padEnd(9)), `${marks.size} in ${displayPath(cli.opts().state)}\n`);
67
- console.log(styleText('bold', `PRs since ${since}`), styleText('dim', `(${prs.length})`));
67
+ console.log(styleText('bold', since == '4' ? 'PRs' : `PRs since ${since}`), styleText('dim', `(${prs.length})`));
68
68
  for (const semver of semvers) {
69
69
  const group = counts[semver];
70
70
  if (!group)
@@ -76,10 +76,13 @@ cli.command('summary', { isDefault: true })
76
76
  .join(', ');
77
77
  console.log(' ', pad(styleText(semverStyles[semver], semver), 11), String(total).padStart(4), ' ', breakdown);
78
78
  }
79
- console.log(styleText('bold', '\nAPIs'), styleText('dim', `(${apis.length} documented)`));
80
- console.log(` ${present} present (${Math.floor((present / apis.length) * 100)}%), ${missing.length} missing and unmarked`);
81
- if (missing.length)
82
- console.log(styleText('red', ' ' + missing.map(({ api }) => api.id).join(', ')));
79
+ const compatPercent = Math.floor((present / apis.length) * 100);
80
+ console.log(styleText('bold', '\nAPI compatibility:'), present + '/' + apis.length, `(${styleText(['bold', compatPercent == 100 ? 'green' : 'yellow'], compatPercent + '%')})`);
81
+ if (missing.length) {
82
+ console.log(styleText('bold', 'Missing APIs:'));
83
+ for (const { api } of missing)
84
+ console.log(' ', styleText('red', api.id));
85
+ }
83
86
  if (pending.length) {
84
87
  console.log(styleText('bold', '\nPending features'), styleText('dim', `(${pending.length})`));
85
88
  printPRTable(pending.slice(0, 15));
@@ -10,7 +10,7 @@ export type MarkEntry = {
10
10
  * Manual marks on PRs (`#<number>`) and APIs (by ID), backed by a JSON file.
11
11
  */
12
12
  export type Marks = Map<string, MarkEntry>;
13
- export declare const defaultMarksPath = ".node-compat.json";
13
+ export declare const defaultMarksPath = "node-compat.json";
14
14
  /**
15
15
  * Opens a marks file, creating it if needed.
16
16
  */
@@ -1,11 +1,11 @@
1
1
  // SPDX-License-Identifier: LGPL-3.0-or-later
2
2
  import { JSONFileMap } from 'utilium/fs';
3
- export const defaultMarksPath = '.node-compat.json';
3
+ export const defaultMarksPath = 'node-compat.json';
4
4
  /**
5
5
  * Opens a marks file, creating it if needed.
6
6
  */
7
7
  export function openMarks(path = defaultMarksPath) {
8
- return new JSONFileMap(path, { overwrite_invalid: false });
8
+ return new JSONFileMap(path, { overwrite_invalid: false, pretty: true });
9
9
  }
10
10
  export function createMark(status, note) {
11
11
  return { status, ...(note && { note }), date: new Date().toISOString().slice(0, 10) };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import assert from 'node:assert/strict';
3
+ import { suite, test } from 'node:test';
4
+ import { config, fs } from '../common.js';
5
+ /**
6
+ * Runs `run` with the process' error listeners replaced, collecting errors that escape callbacks.
7
+ */
8
+ async function collectEscaped(run) {
9
+ const events = ['uncaughtException', 'unhandledRejection'];
10
+ const saved = events.map(event => [event, process.rawListeners(event)]);
11
+ const escaped = [];
12
+ const collect = (error) => escaped.push(error);
13
+ for (const event of events) {
14
+ process.removeAllListeners(event);
15
+ process.on(event, collect);
16
+ }
17
+ try {
18
+ run();
19
+ await new Promise(resolve => setTimeout(resolve, 50));
20
+ }
21
+ finally {
22
+ for (const [event, listeners] of saved) {
23
+ process.removeAllListeners(event);
24
+ for (const listener of listeners)
25
+ process.on(event, listener);
26
+ }
27
+ }
28
+ return escaped;
29
+ }
30
+ suite('Callbacks', config('async'), () => {
31
+ test('a callback that throws is only called once', async () => {
32
+ let calls = 0;
33
+ const thrown = new Error('thrown by callback');
34
+ const escaped = await collectEscaped(() => fs.stat('/', () => {
35
+ calls++;
36
+ throw thrown;
37
+ }));
38
+ assert.equal(calls, 1);
39
+ assert.deepEqual(escaped, [thrown]);
40
+ });
41
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,186 @@
1
+ // SPDX-License-Identifier: LGPL-3.0-or-later
2
+ import assert from 'node:assert/strict';
3
+ import { suite, test } from 'node:test';
4
+ import { config, fs } from '../common.js';
5
+ /** Creates an empty directory for a test, replacing any previous one */
6
+ function fresh(name) {
7
+ const path = '/cp-' + name;
8
+ fs.rmSync(path, { recursive: true, force: true });
9
+ fs.mkdirSync(path);
10
+ return path;
11
+ }
12
+ suite('cp', () => {
13
+ test('errorOnExist throws for an existing directory when force is false', config('sync'), async () => {
14
+ const root = fresh('error-on-exist');
15
+ fs.mkdirSync(root + '/source');
16
+ fs.mkdirSync(root + '/destination');
17
+ const options = { recursive: true, errorOnExist: true, force: false };
18
+ assert.throws(() => fs.cpSync(root + '/source', root + '/destination', options), { code: /EEXIST/ });
19
+ await assert.rejects(fs.promises.cp(root + '/source', root + '/destination', options), { code: /EEXIST/ });
20
+ });
21
+ test('errorOnExist is ignored when force is true', config('sync'), async () => {
22
+ const root = fresh('error-on-exist-force');
23
+ fs.mkdirSync(root + '/source');
24
+ fs.writeFileSync(root + '/source/file', 'new');
25
+ fs.mkdirSync(root + '/destination');
26
+ fs.writeFileSync(root + '/destination/file', 'old');
27
+ fs.cpSync(root + '/source', root + '/destination', { recursive: true, errorOnExist: true });
28
+ assert.equal(fs.readFileSync(root + '/destination/file', 'utf8'), 'new');
29
+ fs.writeFileSync(root + '/destination/file', 'old');
30
+ await fs.promises.cp(root + '/source', root + '/destination', { recursive: true, errorOnExist: true, force: true });
31
+ assert.equal(fs.readFileSync(root + '/destination/file', 'utf8'), 'new');
32
+ });
33
+ test('filter applies to the source itself', config('sync'), async () => {
34
+ const root = fresh('filter-root');
35
+ fs.mkdirSync(root + '/source');
36
+ fs.writeFileSync(root + '/source/file', '');
37
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true, filter: () => false });
38
+ assert(!fs.existsSync(root + '/sync'));
39
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true, filter: () => false });
40
+ assert(!fs.existsSync(root + '/async'));
41
+ });
42
+ test('filter is called once per entry', config('sync'), () => {
43
+ const root = fresh('filter-calls');
44
+ fs.mkdirSync(root + '/source/nested', { recursive: true });
45
+ fs.writeFileSync(root + '/source/nested/file', '');
46
+ const sources = [];
47
+ fs.cpSync(root + '/source', root + '/destination', {
48
+ recursive: true,
49
+ filter: source => (sources.push(source), true),
50
+ });
51
+ assert.deepEqual(sources.map(source => source.slice(source.indexOf(root))), [root + '/source', root + '/source/nested', root + '/source/nested/file']);
52
+ });
53
+ test('cp awaits asynchronous filters', config('sync'), async () => {
54
+ const root = fresh('filter-async');
55
+ fs.mkdirSync(root + '/source');
56
+ fs.writeFileSync(root + '/source/kept', '');
57
+ fs.writeFileSync(root + '/source/skipped', '');
58
+ await fs.promises.cp(root + '/source', root + '/destination', {
59
+ recursive: true,
60
+ filter: async (source) => !source.endsWith('skipped'),
61
+ });
62
+ assert.deepEqual(fs.readdirSync(root + '/destination'), ['kept']);
63
+ });
64
+ test('cpSync rejects asynchronous filters', config('sync'), () => {
65
+ const root = fresh('filter-async-sync');
66
+ fs.mkdirSync(root + '/source');
67
+ assert.throws(() => fs.cpSync(root + '/source', root + '/destination', { recursive: true, filter: (async () => true) }), {
68
+ code: 'ERR_INVALID_RETURN_VALUE',
69
+ });
70
+ });
71
+ test('created directories get the source directory mode', config('sync', 'permissions'), async () => {
72
+ const root = fresh('directory-mode');
73
+ fs.mkdirSync(root + '/source/nested', { recursive: true, mode: 0o750 });
74
+ fs.writeFileSync(root + '/source/nested/file', '');
75
+ fs.chmodSync(root + '/source/nested', 0o550);
76
+ fs.chmodSync(root + '/source', 0o700);
77
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true });
78
+ assert.equal(fs.statSync(root + '/sync').mode & 0o777, 0o700);
79
+ assert.equal(fs.statSync(root + '/sync/nested').mode & 0o777, 0o550);
80
+ assert(fs.existsSync(root + '/sync/nested/file'));
81
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true });
82
+ assert.equal(fs.statSync(root + '/async').mode & 0o777, 0o700);
83
+ assert.equal(fs.statSync(root + '/async/nested').mode & 0o777, 0o550);
84
+ assert(fs.existsSync(root + '/async/nested/file'));
85
+ for (const path of ['/source/nested', '/sync/nested', '/async/nested'])
86
+ fs.chmodSync(root + path, 0o750);
87
+ });
88
+ test('existing symlinks at the destination are replaced', config('sync', 'symlinks'), async () => {
89
+ const root = fresh('existing-symlink');
90
+ fs.mkdirSync(root + '/source');
91
+ fs.mkdirSync(root + '/sync');
92
+ fs.mkdirSync(root + '/async');
93
+ fs.writeFileSync(root + '/old', '');
94
+ fs.writeFileSync(root + '/new', '');
95
+ fs.symlinkSync(root + '/new', root + '/source/link');
96
+ fs.symlinkSync(root + '/old', root + '/sync/link');
97
+ fs.symlinkSync(root + '/old', root + '/async/link');
98
+ fs.cpSync(root + '/source', root + '/sync', { recursive: true });
99
+ assert(fs.readlinkSync(root + '/sync/link', 'utf8').endsWith('/new'));
100
+ await fs.promises.cp(root + '/source', root + '/async', { recursive: true });
101
+ assert(fs.readlinkSync(root + '/async/link', 'utf8').endsWith('/new'));
102
+ });
103
+ test('existing files are kept when force is false', config('sync'), async () => {
104
+ const root = fresh('no-force');
105
+ fs.mkdirSync(root + '/source');
106
+ fs.writeFileSync(root + '/source/existing', 'new');
107
+ fs.writeFileSync(root + '/source/added', 'added');
108
+ fs.utimesSync(root + '/source/existing', 1000, 1000);
109
+ for (const name of ['sync', 'async']) {
110
+ fs.mkdirSync(root + '/' + name);
111
+ fs.writeFileSync(root + '/' + name + '/existing', 'old');
112
+ fs.utimesSync(root + '/' + name + '/existing', 2000, 2000);
113
+ }
114
+ const options = { recursive: true, force: false, preserveTimestamps: true };
115
+ fs.cpSync(root + '/source', root + '/sync', options);
116
+ await fs.promises.cp(root + '/source', root + '/async', options);
117
+ for (const name of ['sync', 'async']) {
118
+ assert.equal(fs.readFileSync(root + '/' + name + '/existing', 'utf8'), 'old');
119
+ assert.equal(fs.statSync(root + '/' + name + '/existing').mtimeMs, 2_000_000);
120
+ assert.equal(fs.readFileSync(root + '/' + name + '/added', 'utf8'), 'added');
121
+ }
122
+ });
123
+ test('dereference copies the targets of symlinks', config('sync', 'symlinks'), async () => {
124
+ const root = fresh('dereference');
125
+ fs.mkdirSync(root + '/directory');
126
+ fs.writeFileSync(root + '/directory/file', 'content');
127
+ fs.writeFileSync(root + '/file', 'content');
128
+ fs.mkdirSync(root + '/source');
129
+ fs.symlinkSync(root + '/directory', root + '/source/directory-link');
130
+ fs.symlinkSync(root + '/file', root + '/source/file-link');
131
+ const options = { recursive: true, dereference: true };
132
+ fs.cpSync(root + '/source', root + '/sync', options);
133
+ await fs.promises.cp(root + '/source', root + '/async', options);
134
+ for (const name of ['sync', 'async']) {
135
+ assert(fs.lstatSync(`${root}/${name}/directory-link`).isDirectory());
136
+ assert.equal(fs.readFileSync(`${root}/${name}/directory-link/file`, 'utf8'), 'content');
137
+ assert(fs.lstatSync(`${root}/${name}/file-link`).isFile());
138
+ }
139
+ fs.cpSync(root + '/source/directory-link', root + '/top-level', options);
140
+ assert(fs.lstatSync(root + '/top-level').isDirectory());
141
+ });
142
+ test('existing destination files are replaced, not written through', config('sync', 'symlinks'), async () => {
143
+ const root = fresh('replace');
144
+ fs.writeFileSync(root + '/source', 'new');
145
+ fs.writeFileSync(root + '/target', 'target');
146
+ for (const name of ['sync', 'async'])
147
+ fs.symlinkSync(root + '/target', `${root}/${name}`);
148
+ const options = { mode: fs.constants.COPYFILE_EXCL };
149
+ fs.cpSync(root + '/source', root + '/sync', options);
150
+ await fs.promises.cp(root + '/source', root + '/async', options);
151
+ for (const name of ['sync', 'async']) {
152
+ assert(fs.lstatSync(`${root}/${name}`).isFile());
153
+ assert.equal(fs.readFileSync(`${root}/${name}`, 'utf8'), 'new');
154
+ }
155
+ assert.equal(fs.readFileSync(root + '/target', 'utf8'), 'target');
156
+ });
157
+ test('copying between directories and non-directories throws', config('sync'), async () => {
158
+ const root = fresh('type-mismatch');
159
+ fs.mkdirSync(root + '/directory');
160
+ fs.writeFileSync(root + '/file', '');
161
+ const toFile = { code: 'ERR_FS_CP_DIR_TO_NON_DIR' };
162
+ assert.throws(() => fs.cpSync(root + '/directory', root + '/file', { recursive: true }), toFile);
163
+ await assert.rejects(fs.promises.cp(root + '/directory', root + '/file', { recursive: true }), toFile);
164
+ const toDirectory = { code: 'ERR_FS_CP_NON_DIR_TO_DIR' };
165
+ assert.throws(() => fs.cpSync(root + '/file', root + '/directory'), toDirectory);
166
+ await assert.rejects(fs.promises.cp(root + '/file', root + '/directory'), toDirectory);
167
+ });
168
+ test('invalid copies throw Node error codes', config('sync'), async () => {
169
+ const root = fresh('errors');
170
+ fs.mkdirSync(root + '/directory');
171
+ fs.writeFileSync(root + '/file', 'contents');
172
+ fs.writeFileSync(root + '/existing', '');
173
+ const cases = [
174
+ ['same file', [root + '/file', root + '/file'], { code: 'ERR_FS_CP_EINVAL', errno: 22 }],
175
+ ['subdirectory of self', [root + '/directory', root + '/directory/sub', { recursive: true }], { code: 'ERR_FS_CP_EINVAL', errno: 22 }],
176
+ ['directory without recursive', [root + '/directory', root + '/copy'], { code: 'ERR_FS_EISDIR', errno: 21 }],
177
+ ['errorOnExist', [root + '/file', root + '/existing', { force: false, errorOnExist: true }], { code: 'ERR_FS_CP_EEXIST', errno: 17 }],
178
+ ];
179
+ for (const [name, args, expected] of cases) {
180
+ assert.throws(() => fs.cpSync(...args), { code: expected.code }, name);
181
+ await assert.rejects(fs.promises.cp(...args), { name: 'SystemError', syscall: 'cp', ...expected }, name);
182
+ }
183
+ assert.equal(fs.readFileSync(root + '/file', 'utf8'), 'contents');
184
+ assert(!fs.existsSync(root + '/directory/sub'));
185
+ });
186
+ });
@@ -60,11 +60,40 @@ suite('Dir', config('directories'), () => {
60
60
  assert(testFiles.includes(dirents[0].name));
61
61
  assert(testFiles.includes(dirents[1].name));
62
62
  });
63
+ test('recursive', async () => {
64
+ fs.mkdirSync('dir-recursive/nested', { recursive: true });
65
+ fs.writeFileSync('dir-recursive/top.txt', '');
66
+ fs.writeFileSync('dir-recursive/nested/deep.txt', '');
67
+ const expected = ['nested', 'nested/deep.txt', 'top.txt'];
68
+ const relative = (dirent) => (dirent.parentPath.endsWith('nested') ? 'nested/' : '') + dirent.name;
69
+ const dir = fs.opendirSync('dir-recursive', { recursive: true });
70
+ const names = [];
71
+ for (let dirent; (dirent = dir.readSync());)
72
+ names.push(relative(dirent));
73
+ dir.closeSync();
74
+ assert.deepEqual(names.sort(), expected);
75
+ const asyncNames = [];
76
+ for await (const dirent of await fs.promises.opendir('dir-recursive', { recursive: true, bufferSize: 1 }))
77
+ asyncNames.push(relative(dirent));
78
+ assert.deepEqual(asyncNames.sort(), expected);
79
+ });
63
80
  test('read after directory is closed', config('async'), async () => {
64
81
  const dir = fs.opendirSync(testDirPath);
65
82
  await dir.close();
66
83
  await assert.rejects(dir.read());
67
84
  });
85
+ test('read with a callback', config('async'), async () => {
86
+ const dir = fs.opendirSync(testDirPath);
87
+ const { promise, resolve, reject } = Promise.withResolvers();
88
+ dir.read((error, dirent) => (error ? reject(error) : resolve(dirent)));
89
+ assert(testFiles.includes((await promise).name));
90
+ await dir.close();
91
+ });
92
+ test('read with a callback after directory is closed', config('async'), async () => {
93
+ const dir = fs.opendirSync(testDirPath);
94
+ await dir.close();
95
+ assert.throws(() => dir.read(() => { }), { code: 'ERR_DIR_CLOSED' });
96
+ });
68
97
  test('readSync after directory is closed', config('sync'), () => {
69
98
  const dir = fs.opendirSync(testDirPath);
70
99
  dir.closeSync();
@@ -75,6 +104,17 @@ suite('Dir', config('directories'), () => {
75
104
  await dir.close();
76
105
  await assert.rejects(dir.close(), { code: 'ERR_DIR_CLOSED' });
77
106
  });
107
+ test('close with a callback multiple times', config('async'), async () => {
108
+ const dir = fs.opendirSync(testDirPath);
109
+ dir.closeSync();
110
+ let isSync = true;
111
+ const { promise, resolve } = Promise.withResolvers();
112
+ dir.close(error => resolve([error, isSync]));
113
+ isSync = false;
114
+ const [error, calledSynchronously] = await promise;
115
+ assert.equal(error?.code, 'ERR_DIR_CLOSED');
116
+ assert(!calledSynchronously);
117
+ });
78
118
  test('closeSync multiple times', config('sync'), () => {
79
119
  const dir = fs.opendirSync(testDirPath);
80
120
  dir.closeSync();
@@ -57,6 +57,13 @@ suite('Directories', config('directories'), () => {
57
57
  assert.throws(() => fs.mkdirSync('/recursiveSF', { recursive: true }), { code: 'EEXIST', path: '/recursiveSF' });
58
58
  assert.throws(() => fs.mkdirSync('/recursiveSF/A/B', { recursive: true }), { code: 'ENOTDIR', path: '/recursiveSF/A/B' });
59
59
  });
60
+ test('rmdir with options and a callback', config('async'), async () => {
61
+ await fs.promises.mkdir('/rmdir-callback');
62
+ const { promise, resolve } = Promise.withResolvers();
63
+ fs.rmdir('/rmdir-callback', {}, resolve);
64
+ assert.equal(await promise, null);
65
+ assert(!fs.existsSync('/rmdir-callback'));
66
+ });
60
67
  test('rmdir (non-empty)', config('async'), async () => {
61
68
  await fs.promises.mkdir('/rmdirTest');
62
69
  await fs.promises.mkdir('/rmdirTest/rmdirTest2');
@@ -80,6 +87,28 @@ suite('Directories', config('directories'), () => {
80
87
  await fs.promises.writeFile('/rmDirRecursively/rmDirNested/test.txt', 'hello world!');
81
88
  await fs.promises.rm('/rmDirRecursively', { recursive: true });
82
89
  });
90
+ test('rm on a directory without recursive', async () => {
91
+ const path = '/rm-directory';
92
+ fs.mkdirSync(path);
93
+ const expected = {
94
+ name: 'SystemError',
95
+ code: 'ERR_FS_EISDIR',
96
+ errno: 21,
97
+ syscall: 'rm',
98
+ path,
99
+ message: `Path is a directory: rm returned EISDIR (is a directory) ${path}`,
100
+ };
101
+ assert.throws(() => fs.rmSync(path), expected);
102
+ assert.throws(() => fs.rmSync(path, { force: true }), expected);
103
+ await assert.rejects(fs.promises.rm(path), expected);
104
+ const { promise, resolve } = Promise.withResolvers();
105
+ fs.rm(path, resolve);
106
+ const error = await promise;
107
+ assert.throws(() => {
108
+ throw error;
109
+ }, expected);
110
+ assert(fs.statSync(path).isDirectory());
111
+ });
83
112
  test('rmSync recursively', config('sync'), () => {
84
113
  fs.mkdirSync('/rmDirRecursively');
85
114
  fs.mkdirSync('/rmDirRecursively/rmDirNested');
@@ -133,6 +162,19 @@ suite('Directories', config('directories'), () => {
133
162
  assert.deepEqual(values[4], ['/' + testDir + '/subdir1', 'file4.txt']);
134
163
  assert.deepEqual(values[8], ['/' + testDir + '/subdir2', 'file5.txt']);
135
164
  });
165
+ test('readdir is not affected by mutating options after the call', config('async'), async () => {
166
+ const options = { recursive: true, withFileTypes: false };
167
+ const promise = fs.promises.readdir(testDir, options);
168
+ options.recursive = false;
169
+ options.withFileTypes = true;
170
+ const entries = await promise;
171
+ assert(entries.includes('subdir1/file4.txt'));
172
+ assert(entries.every(entry => typeof entry == 'string'));
173
+ });
174
+ test('Dirent does not have path', config('sync'), () => {
175
+ const [entry] = fs.readdirSync(testDir, { withFileTypes: true });
176
+ assert(!('path' in entry));
177
+ });
136
178
  test('readdirSync returns files recursively', config('sync'), () => {
137
179
  const entries = fs.readdirSync(testDir, { recursive: true }).sort();
138
180
  assert.equal(entries[0], 'file1.txt');
@@ -20,6 +20,42 @@ suite('Links', config('symlinks'), () => {
20
20
  assert.equal(stats.mode & 0o7777, 0o777);
21
21
  fs.unlinkSync('symlink-sync.js');
22
22
  });
23
+ test('symlink type may be null', async () => {
24
+ fs.symlinkSync(target, 'symlink-null-sync.js', null);
25
+ assert(fs.lstatSync('symlink-null-sync.js').isSymbolicLink());
26
+ fs.unlinkSync('symlink-null-sync.js');
27
+ await fs.promises.symlink(target, 'symlink-null.js', null);
28
+ assert((await fs.promises.lstat('symlink-null.js')).isSymbolicLink());
29
+ await fs.promises.unlink('symlink-null.js');
30
+ });
31
+ test('symlink rejects invalid types', () => {
32
+ assert.throws(() => fs.symlinkSync(target, 'symlink-invalid.js', 'bogus'), TypeError);
33
+ });
34
+ test('realpath.native resolves like realpath', async () => {
35
+ const expected = fs.realpathSync(symlink);
36
+ assert.equal(fs.realpathSync.native(symlink), expected);
37
+ const { promise, resolve, reject } = Promise.withResolvers();
38
+ fs.realpath.native(symlink, (error, resolved) => (error ? reject(error) : resolve(resolved)));
39
+ assert.equal(await promise, expected);
40
+ });
41
+ test('readlink returns a string unless the encoding is buffer', async () => {
42
+ const link = fs.readlinkSync(symlink);
43
+ assert.equal(typeof link, 'string');
44
+ assert(Buffer.isBuffer(fs.readlinkSync(symlink, { encoding: 'buffer' })));
45
+ const { promise, resolve, reject } = Promise.withResolvers();
46
+ fs.readlink(symlink, { encoding: 'buffer' }, (error, result) => (error ? reject(error) : resolve(result)));
47
+ assert(Buffer.isBuffer(await promise));
48
+ });
49
+ test('symlink onto an existing entry throws EEXIST for the link', async () => {
50
+ fs.symlinkSync('/does-not-exist', 'symlink-broken.js');
51
+ for (const existing of [target, symlink, 'symlink-broken.js']) {
52
+ const error = (thrown) => thrown.code == 'EEXIST' && thrown.syscall == 'symlink' && thrown.path == 'other' && thrown.dest.endsWith(existing);
53
+ assert.throws(() => fs.symlinkSync('other', existing), error);
54
+ await assert.rejects(fs.promises.symlink('other', existing), error);
55
+ }
56
+ assert.equal(fs.readlinkSync('symlink-broken.js', 'utf8'), '/does-not-exist');
57
+ fs.unlinkSync('symlink-broken.js');
58
+ });
23
59
  test('lstat file inside symlinked directory #241', async () => {
24
60
  await fs.promises.mkdir('/a');
25
61
  await fs.promises.writeFile('/a/hello.txt', 'hello world');
@@ -92,4 +92,19 @@ suite('Opening files', () => {
92
92
  await result_2;
93
93
  }
94
94
  });
95
+ test('flags default to "r"', async () => {
96
+ fs.closeSync(fs.openSync(filename));
97
+ fs.closeSync(fs.openSync(filename, undefined));
98
+ assert.throws(() => fs.writeSync(fs.openSync(filename), 'x'), { code: 'EBADF' });
99
+ const handle = await fs.promises.open(filename);
100
+ await handle.close();
101
+ const { promise, resolve, reject } = Promise.withResolvers();
102
+ fs.open(filename, (error, fd) => (error ? reject(error) : resolve(fd)));
103
+ fs.closeSync(await promise);
104
+ });
105
+ test('Windows-only open flags are 0', () => {
106
+ for (const name of ['UV_FS_O_FILEMAP', 'UV_FS_O_TEMPORARY', 'UV_FS_O_SHORT_LIVED', 'UV_FS_O_SEQUENTIAL', 'UV_FS_O_RANDOM']) {
107
+ assert.equal(fs.constants[name], 0, name);
108
+ }
109
+ });
95
110
  });
@@ -131,6 +131,95 @@ suite('read', () => {
131
131
  assert.equal(buffer.subarray(10, buffer.length).toString(), expected);
132
132
  assert.equal(bytesRead, expected.length);
133
133
  });
134
+ test('fractional read lengths are truncated asynchronously', config('async'), async () => {
135
+ const env_3 = { stack: [], error: void 0, hasError: false };
136
+ try {
137
+ const handle = __addDisposableResource(env_3, await fs.promises.open(filepath, 'r'), true);
138
+ const { bytesRead } = await handle.read(Buffer.alloc(expected.length), 0, 2.7, 0);
139
+ assert.equal(bytesRead, 2);
140
+ }
141
+ catch (e_3) {
142
+ env_3.error = e_3;
143
+ env_3.hasError = true;
144
+ }
145
+ finally {
146
+ const result_3 = __disposeResources(env_3);
147
+ if (result_3)
148
+ await result_3;
149
+ }
150
+ });
151
+ test('fractional read lengths are truncated synchronously', config('sync'), () => {
152
+ const fd = fs.openSync(filepath, 'r');
153
+ assert.equal(fs.readSync(fd, Buffer.alloc(expected.length), 0, 2.7, 0), 2);
154
+ fs.closeSync(fd);
155
+ });
156
+ test('read with an options object and a callback', config('async'), async () => {
157
+ const fd = fs.openSync(filepath, 'r');
158
+ const read = (...args) => {
159
+ const { promise, resolve, reject } = Promise.withResolvers();
160
+ fs.read(fd, ...args, (error, bytesRead, buffer) => error ? reject(error) : resolve([bytesRead, buffer]));
161
+ return promise;
162
+ };
163
+ const [bytesRead, buffer] = await read(Buffer.alloc(expected.length), { length: 2, position: 0 });
164
+ assert.equal(bytesRead, 2);
165
+ assert.equal(buffer.subarray(0, 2).toString(), expected.slice(0, 2));
166
+ const target = Buffer.alloc(expected.length);
167
+ const [bytesReadWithBuffer, bufferFromOptions] = await read({ buffer: target, position: 0 });
168
+ assert.equal(bytesReadWithBuffer, expected.length);
169
+ assert.equal(bufferFromOptions, target);
170
+ assert.equal(target.toString(), expected);
171
+ fs.closeSync(fd);
172
+ });
173
+ test('positional reads do not move the file position', config('sync'), async () => {
174
+ const env_4 = { stack: [], error: void 0, hasError: false };
175
+ try {
176
+ const fd = fs.openSync(filepath, 'r');
177
+ const buffer = Buffer.alloc(1);
178
+ fs.readSync(fd, buffer, 0, 1, null);
179
+ fs.readSync(fd, buffer, 0, 1, 3);
180
+ fs.readSync(fd, buffer, 0, 1, null);
181
+ assert.equal(buffer.toString(), expected[1]);
182
+ fs.closeSync(fd);
183
+ const handle = __addDisposableResource(env_4, await fs.promises.open(filepath, 'r'), true);
184
+ await handle.read(buffer, 0, 1, null);
185
+ await handle.read(buffer, 0, 1, 3);
186
+ await handle.read(buffer, 0, 1, null);
187
+ assert.equal(buffer.toString(), expected[1]);
188
+ }
189
+ catch (e_4) {
190
+ env_4.error = e_4;
191
+ env_4.hasError = true;
192
+ }
193
+ finally {
194
+ const result_4 = __disposeResources(env_4);
195
+ if (result_4)
196
+ await result_4;
197
+ }
198
+ });
199
+ test('readv reads at the current position', config('sync'), async () => {
200
+ const env_5 = { stack: [], error: void 0, hasError: false };
201
+ try {
202
+ const fd = fs.openSync(filepath, 'r');
203
+ const [first, second] = [Buffer.alloc(1), Buffer.alloc(2)];
204
+ assert.equal(fs.readvSync(fd, [first]), 1);
205
+ assert.equal(fs.readvSync(fd, [second]), 2);
206
+ assert.equal(first.toString() + second.toString(), expected.slice(0, 3));
207
+ fs.closeSync(fd);
208
+ const handle = __addDisposableResource(env_5, await fs.promises.open(filepath, 'r'), true);
209
+ await handle.readv([first], 2);
210
+ await handle.readv([second]);
211
+ assert.equal(first.toString() + second.toString(), expected[2] + expected.slice(0, 2));
212
+ }
213
+ catch (e_5) {
214
+ env_5.error = e_5;
215
+ env_5.hasError = true;
216
+ }
217
+ finally {
218
+ const result_5 = __disposeResources(env_5);
219
+ if (result_5)
220
+ await result_5;
221
+ }
222
+ });
134
223
  test('read using callback API #239', config('sync', 'write'), async () => {
135
224
  const path = '/text.txt';
136
225
  fs.writeFileSync(path, 'hello world');
@@ -138,12 +227,60 @@ suite('read', () => {
138
227
  const fd = (await promisify(fs.open)(path, 0, 0));
139
228
  const read = promisify(fs.read);
140
229
  const buf = Buffer.alloc(1024);
141
- const n0 = await read(fd, buf, 0, 1024, undefined);
230
+ const { bytesRead: n0 } = await read(fd, buf, 0, 1024, null);
142
231
  assert.equal(n0, 11);
143
232
  assert.equal(buf.subarray(0, n0).toString('utf8'), 'hello world');
144
- const n1 = await read(fd, buf, 0, 1024, undefined);
233
+ const { bytesRead: n1 } = await read(fd, buf, 0, 1024, null);
145
234
  assert.equal(n1, 0);
146
235
  assert.equal(buf.subarray(0, n1).toString('utf8'), '');
147
236
  await promisify(fs.close)(fd);
148
237
  });
238
+ test('util.promisify resolves with named results', config('async'), async () => {
239
+ const path = 'promisify-results.txt';
240
+ fs.writeFileSync(path, 'abc');
241
+ const fd = fs.openSync(path, 'r+');
242
+ const read = await promisify(fs.read)(fd, Buffer.alloc(3), 0, 3, 0);
243
+ assert.equal(read.bytesRead, 3);
244
+ assert.equal(read.buffer.toString(), 'abc');
245
+ const written = await promisify(fs.write)(fd, Buffer.from('xy'), 0, 2, 0);
246
+ assert.equal(written.bytesWritten, 2);
247
+ assert.equal(written.buffer.toString(), 'xy');
248
+ const readv = await promisify(fs.readv)(fd, [Buffer.alloc(3)], 0);
249
+ assert.equal(readv.bytesRead, 3);
250
+ assert.equal(readv.buffers[0].toString(), 'xyc');
251
+ const writev = await promisify(fs.writev)(fd, [Buffer.from('z')], 0);
252
+ assert.equal(writev.bytesWritten, 1);
253
+ assert.equal(writev.buffer.length, 1);
254
+ fs.closeSync(fd);
255
+ assert.equal(await promisify(fs.exists)(path), true);
256
+ assert.equal(await promisify(fs.exists)('promisify-missing.txt'), false);
257
+ });
258
+ test('reads without a buffer allocate 16 KiB', config('async'), async () => {
259
+ const env_6 = { stack: [], error: void 0, hasError: false };
260
+ try {
261
+ const handle = __addDisposableResource(env_6, await fs.promises.open(filepath, 'r'), true);
262
+ for (const result of [await handle.read(), await handle.read({ position: 0 })]) {
263
+ assert(Buffer.isBuffer(result.buffer));
264
+ assert.equal(result.buffer.length, 16384);
265
+ }
266
+ const fd = fs.openSync(filepath, 'r');
267
+ const { promise, resolve, reject } = Promise.withResolvers();
268
+ fs.read(fd, (error, bytesRead, buffer) => (error ? reject(error) : resolve([bytesRead, buffer])));
269
+ const [bytesRead, buffer] = await promise;
270
+ fs.closeSync(fd);
271
+ assert.equal(bytesRead, expected.length);
272
+ assert(Buffer.isBuffer(buffer));
273
+ assert.equal(buffer.byteLength, 16384);
274
+ assert.equal(buffer.subarray(0, bytesRead).toString(), expected);
275
+ }
276
+ catch (e_6) {
277
+ env_6.error = e_6;
278
+ env_6.hasError = true;
279
+ }
280
+ finally {
281
+ const result_6 = __disposeResources(env_6);
282
+ if (result_6)
283
+ await result_6;
284
+ }
285
+ });
149
286
  });