All files / src/node FileHandle.ts

77.45% Statements 79/102
75% Branches 27/36
88.23% Functions 30/34
76.53% Lines 75/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 28365x 65x         65x   1077x 1077x     1077x 1077x         1077x 1077x 1077x           1x       2x       2x       2x       1054x 2x     1052x       1052x 1052x 1052x 1052x 1052x       1052x                         1052x 1052x       2x       1x       1x       12x 12x   12x 2x     10x       10x 1x         9x 9x   9x 9x 9x 9x 1x           9x         15x 15x 15x                               15x   15x 7x 7x 7x     8x 8x               2x                     29x   29x                 28x 11x     28x       2x       2x       2x               9x       2x                 1017x   1017x                 1016x 8x     1016x       2x       2x         1x       9x       9x 9x                                                        
import { promisify } from './util';
import { EventEmitter } from 'events';
import type * as opts from './types/options';
import type { IFileHandle, IReadStream, IWriteStream, IStats, TData, TDataOut, TMode, TTime } from './types/misc';
import type { FsCallbackApi } from './types';
 
export class FileHandle extends EventEmitter implements IFileHandle {
  private fs: FsCallbackApi;
  private refs: number = 1;
  private closePromise: Promise<void> | null = null;
  private closeResolve?: () => void;
  private closeReject?: (error: Error) => void;
  private position: number = 0;
  private readableWebStreamLocked: boolean = false;
 
  fd: number;
 
  constructor(fs: FsCallbackApi, fd: number) {
    super();
    this.fs = fs;
    this.fd = fd;
  }
 
  getAsyncId(): number {
    // Return a unique async ID for this file handle
    // In a real implementation, this would be provided by the underlying system
    return this.fd;
  }
 
  appendFile(data: TData, options?: opts.IAppendFileOptions | string): Promise<void> {
    return promisify(this.fs, 'appendFile')(this.fd, data, options);
  }
 
  chmod(mode: TMode): Promise<void> {
    return promisify(this.fs, 'fchmod')(this.fd, mode);
  }
 
  chown(uid: number, gid: number): Promise<void> {
    return promisify(this.fs, 'fchown')(this.fd, uid, gid);
  }
 
  close(): Promise<void> {
    if (this.fd === -1) {
      return Promise.resolve();
    }
 
    Iif (this.closePromise) {
      return this.closePromise;
    }
 
    this.refs--;
    if (this.refs === 0) {
      const currentFd = this.fd;
      this.fd = -1;
      this.closePromise = promisify(
        this.fs,
        'close',
      )(currentFd).finally(() => {
        this.closePromise = null;
      });
    } else E{
      this.closePromise = new Promise<void>((resolve, reject) => {
        this.closeResolve = resolve;
        this.closeReject = reject;
      }).finally(() => {
        this.closePromise = null;
        this.closeReject = undefined;
        this.closeResolve = undefined;
      });
    }
 
    this.emit('close');
    return this.closePromise;
  }
 
  datasync(): Promise<void> {
    return promisify(this.fs, 'fdatasync')(this.fd);
  }
 
  createReadStream(options: opts.IFileHandleReadStreamOptions): IReadStream {
    return this.fs.createReadStream('', { ...options, fd: this });
  }
 
  createWriteStream(options: opts.IFileHandleWriteStreamOptions): IWriteStream {
    return this.fs.createWriteStream('', { ...options, fd: this });
  }
 
  readableWebStream(options: opts.IReadableWebStreamOptions = {}): ReadableStream {
    const { type = 'bytes', autoClose = false } = options;
    let position = 0;
 
    if (this.fd === -1) {
      throw new Error('The FileHandle is closed');
    }
 
    Iif (this.closePromise) {
      throw new Error('The FileHandle is closing');
    }
 
    if (this.readableWebStreamLocked) {
      throw new Error(
        'An error will be thrown if this method is called more than once or is called after the FileHandle is closed or closing.',
      );
    }
 
    this.readableWebStreamLocked = true;
    this.ref();
 
    const unlockAndCleanup = () => {
      this.readableWebStreamLocked = false;
      this.unref();
      if (autoClose) {
        this.close().catch(() => {
          // Ignore close errors in cleanup
        });
      }
    };
 
    return new ReadableStream({
      type: type === 'bytes' ? 'bytes' : undefined,
      autoAllocateChunkSize: 16384,
 
      pull: async (controller: any) => {
        try {
          const view = controller.byobRequest?.view;
          Iif (!view) {
            // Fallback for when BYOB is not available
            const buffer = new Uint8Array(16384);
            const result = await this.read(buffer, 0, buffer.length, position);
 
            Iif (result.bytesRead === 0) {
              controller.close();
              unlockAndCleanup();
              return;
            }
 
            position += result.bytesRead;
            controller.enqueue(buffer.slice(0, result.bytesRead));
            return;
          }
 
          const result = await this.read(view as Uint8Array, view.byteOffset, view.byteLength, position);
 
          if (result.bytesRead === 0) {
            controller.close();
            unlockAndCleanup();
            return;
          }
 
          position += result.bytesRead;
          controller.byobRequest.respond(result.bytesRead);
        } catch (error) {
          controller.error(error);
          unlockAndCleanup();
        }
      },
 
      cancel: async () => {
        unlockAndCleanup();
      },
    });
  }
 
  async read(
    buffer: Buffer | Uint8Array,
    offset: number,
    length: number,
    position?: number | null,
  ): Promise<TFileHandleReadResult> {
    const readPosition = position !== null && position !== undefined ? position : this.position;
 
    const result = await promisify(this.fs, 'read', bytesRead => ({ bytesRead, buffer }))(
      this.fd,
      buffer,
      offset,
      length,
      readPosition,
    );
 
    // Update internal position only if position was null/undefined
    if (position === null || position === undefined) {
      this.position += result.bytesRead;
    }
 
    return result;
  }
 
  readv(buffers: ArrayBufferView[], position?: number | null | undefined): Promise<TFileHandleReadvResult> {
    return promisify(this.fs, 'readv', bytesRead => ({ bytesRead, buffers }))(this.fd, buffers, position);
  }
 
  readFile(options?: opts.IReadFileOptions | string): Promise<TDataOut> {
    return promisify(this.fs, 'readFile')(this.fd, options);
  }
 
  stat(options?: opts.IFStatOptions): Promise<IStats> {
    return promisify(this.fs, 'fstat')(this.fd, options);
  }
 
  sync(): Promise<void> {
    return promisify(this.fs, 'fsync')(this.fd);
  }
 
  truncate(len?: number): Promise<void> {
    return promisify(this.fs, 'ftruncate')(this.fd, len);
  }
 
  utimes(atime: TTime, mtime: TTime): Promise<void> {
    return promisify(this.fs, 'futimes')(this.fd, atime, mtime);
  }
 
  async write(
    buffer: Buffer | Uint8Array,
    offset?: number,
    length?: number,
    position?: number | null,
  ): Promise<TFileHandleWriteResult> {
    const writePosition = position !== null && position !== undefined ? position : this.position;
 
    const result = await promisify(this.fs, 'write', bytesWritten => ({ bytesWritten, buffer }))(
      this.fd,
      buffer,
      offset,
      length,
      writePosition,
    );
 
    // Update internal position only if position was null/undefined
    if (position === null || position === undefined) {
      this.position += result.bytesWritten;
    }
 
    return result;
  }
 
  writev(buffers: ArrayBufferView[], position?: number | null | undefined): Promise<TFileHandleWritevResult> {
    return promisify(this.fs, 'writev', bytesWritten => ({ bytesWritten, buffers }))(this.fd, buffers, position);
  }
 
  writeFile(data: TData, options?: opts.IWriteFileOptions): Promise<void> {
    return promisify(this.fs, 'writeFile')(this.fd, data, options);
  }
 
  // Implement Symbol.asyncDispose if available (ES2023+)
  async [(Symbol as any).asyncDispose](): Promise<void> {
    await this.close();
  }
 
  private ref(): void {
    this.refs++;
  }
 
  private unref(): void {
    this.refs--;
    Iif (this.refs === 0) {
      this.fd = -1;
      Iif (this.closeResolve) {
        promisify(this.fs, 'close')(this.fd).then(this.closeResolve, this.closeReject);
      }
    }
  }
}
 
export interface TFileHandleReadResult {
  bytesRead: number;
  buffer: Buffer | Uint8Array;
}
 
export interface TFileHandleWriteResult {
  bytesWritten: number;
  buffer: Buffer | Uint8Array;
}
 
export interface TFileHandleReadvResult {
  bytesRead: number;
  buffers: ArrayBufferView[];
}
 
export interface TFileHandleWritevResult {
  bytesWritten: number;
  buffers: ArrayBufferView[];
}