All files / src/fsa-to-node FsaNodeFsOpenFile.ts

94.11% Statements 16/17
50% Branches 1/2
100% Functions 3/3
93.75% Lines 15/16

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                1x 34x                     34x 34x 34x 34x 34x   34x           5x   5x 5x 5x         5x 5x 5x      
import { FLAG_CON } from '../consts/FLAG';
import type * as fsa from '../fsa/types';
import type * as misc from '../node/types/misc';
 
/**
 * Represents an open file. Stores additional metadata about the open file, such
 * as the seek position.
 */
export class FsaNodeFsOpenFile {
  protected seek: number = 0;
 
  /**
   * This influences the behavior of the next write operation. On the first
   * write we want to overwrite the file or keep the existing data, depending
   * with which flags the file was opened. On subsequent writes we want to
   * append to the file.
   */
  protected keepExistingData: boolean;
 
  public constructor(
    public readonly fd: number,
    public readonly createMode: misc.TMode,
    public readonly flags: number,
    public readonly file: fsa.IFileSystemFileHandle,
    public readonly filename: string,
  ) {
    this.keepExistingData = !!(flags & FLAG_CON.O_APPEND);
  }
 
  public async close(): Promise<void> {}
 
  public async write(data: ArrayBufferView, seek: number | null): Promise<void> {
    if (typeof seek !== 'number') seek = this.seek;
    else Ethis.keepExistingData = true;
    const keepExistingData = this.keepExistingData;
    const writer = await this.file.createWritable({ keepExistingData });
    await writer.write({
      type: 'write',
      data,
      position: seek,
    });
    await writer.close();
    this.keepExistingData = true;
    this.seek += data.byteLength;
  }
}