|
9 | 9 | } = primordials; |
10 | 10 |
|
11 | 11 | const { Buffer } = require('buffer'); |
| 12 | +const { isArrayBufferView } = require('internal/util/types'); |
12 | 13 | const { resolve, sep } = require('path'); |
13 | 14 | const { fileURLToPath, URL } = require('internal/url'); |
14 | 15 | const { kEmptyObject } = require('internal/util'); |
@@ -46,6 +47,31 @@ function noopFd(fd) { |
46 | 47 | return undefined; |
47 | 48 | } |
48 | 49 |
|
| 50 | +function toWriteBuffer(data, options) { |
| 51 | + if (Buffer.isBuffer(data)) return data; |
| 52 | + if (isArrayBufferView(data)) { |
| 53 | + return Buffer.from(data.buffer, data.byteOffset, data.byteLength); |
| 54 | + } |
| 55 | + const encoding = typeof options === 'string' ? options : options?.encoding; |
| 56 | + return Buffer.from(data, encoding || 'utf8'); |
| 57 | +} |
| 58 | + |
| 59 | +function writeFileSyncFd(fd, data, options) { |
| 60 | + const vfd = getVirtualFd(fd); |
| 61 | + if (vfd === undefined) return undefined; |
| 62 | + |
| 63 | + const buffer = toWriteBuffer(data, options); |
| 64 | + let offset = 0; |
| 65 | + let length = buffer.byteLength; |
| 66 | + while (length > 0) { |
| 67 | + const written = vfd.entry.writeSync(buffer, offset, length, null); |
| 68 | + offset += written; |
| 69 | + length -= written; |
| 70 | + } |
| 71 | + |
| 72 | + return true; |
| 73 | +} |
| 74 | + |
49 | 75 | // Registry of active VFS instances. |
50 | 76 | const activeVFSList = []; |
51 | 77 |
|
@@ -288,10 +314,14 @@ function createVfsHandlers() { |
288 | 314 |
|
289 | 315 | // ==================== Sync path-based write ops ==================== |
290 | 316 |
|
291 | | - writeFileSync: (path, data, options) => |
292 | | - vfsOpVoid(path, (vfs, n) => vfs.writeFileSync(n, data, options)), |
293 | | - appendFileSync: (path, data, options) => |
294 | | - vfsOpVoid(path, (vfs, n) => vfs.appendFileSync(n, data, options)), |
| 317 | + writeFileSync(path, data, options) { |
| 318 | + if (typeof path === 'number') return writeFileSyncFd(path, data, options); |
| 319 | + return vfsOpVoid(path, (vfs, n) => vfs.writeFileSync(n, data, options)); |
| 320 | + }, |
| 321 | + appendFileSync(path, data, options) { |
| 322 | + if (typeof path === 'number') return writeFileSyncFd(path, data, options); |
| 323 | + return vfsOpVoid(path, (vfs, n) => vfs.appendFileSync(n, data, options)); |
| 324 | + }, |
295 | 325 | mkdirSync: (path, options) => |
296 | 326 | vfsOp(path, (vfs, n) => ({ result: vfs.mkdirSync(n, options) })), |
297 | 327 | rmdirSync: (path) => vfsOpVoid(path, (vfs, n) => vfs.rmdirSync(n)), |
|
0 commit comments