diff options
author | nasa <htilcs1115@gmail.com> | 2023-06-08 23:47:12 +0900 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-06-08 08:47:12 -0600 |
commit | caad79ef7807bbd8f53b0338e23d281c5c45519b (patch) | |
tree | c26d874f1bd5f8ac52c129329ca26a50bf13a2fd /ext/node/polyfills/internal/fs/handle.ts | |
parent | 262571e63e3086e0a4ea6125b3836c357a21af86 (diff) |
feat(node_compat): Add a write method to the FileHandle class (#19385)
## WHY
ref: https://github.com/denoland/deno/issues/19165
The FileHandle class has many missing methods compared to node.
## WHAT
Add write method
Diffstat (limited to 'ext/node/polyfills/internal/fs/handle.ts')
-rw-r--r-- | ext/node/polyfills/internal/fs/handle.ts | 63 |
1 files changed, 61 insertions, 2 deletions
diff --git a/ext/node/polyfills/internal/fs/handle.ts b/ext/node/polyfills/internal/fs/handle.ts index 199457787..fbe535840 100644 --- a/ext/node/polyfills/internal/fs/handle.ts +++ b/ext/node/polyfills/internal/fs/handle.ts @@ -1,8 +1,7 @@ // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. import { EventEmitter } from "ext:deno_node/events.ts"; import { Buffer } from "ext:deno_node/buffer.ts"; -import { promises, read } from "ext:deno_node/fs.ts"; -import type { Buffer } from "ext:deno_node/buffer.ts"; +import { promises, read, write } from "ext:deno_node/fs.ts"; import { BinaryOptionsArgument, FileOptionsArgument, @@ -10,6 +9,11 @@ import { TextOptionsArgument, } from "ext:deno_node/_fs/_fs_common.ts"; +interface WriteResult { + bytesWritten: number; + buffer: Buffer | string; +} + interface ReadResult { bytesRead: number; buffer: Buffer; @@ -69,6 +73,61 @@ export class FileHandle extends EventEmitter { return promises.readFile(this, opt); } + write( + buffer: Buffer, + offset: number, + length: number, + position: number, + ): Promise<WriteResult>; + write( + str: string, + position: number, + encoding: string, + ): Promise<WriteResult>; + write( + bufferOrStr: Buffer | string, + offsetOrPotition: number, + lengthOrEncoding: number | string, + position?: number, + ): Promise<WriteResult> { + if (bufferOrStr instanceof Buffer) { + const buffer = bufferOrStr; + const offset = offsetOrPotition; + const length = lengthOrEncoding; + + return new Promise((resolve, reject) => { + write( + this.fd, + buffer, + offset, + length, + position, + (err, bytesWritten, buffer) => { + if (err) reject(err); + else resolve({ buffer, bytesWritten }); + }, + ); + }); + } else { + const str = bufferOrStr; + const position = offsetOrPotition; + const encoding = lengthOrEncoding; + + return new Promise((resolve, reject) => { + write( + this.fd, + str, + position, + encoding, + (err, bytesWritten, buffer) => { + if (err) reject(err); + else resolve({ buffer, bytesWritten }); + }, + ); + }); + } + } + close(): Promise<void> { // Note that Deno.close is not async return Promise.resolve(Deno.close(this.fd)); |