All files / src/core File.ts

86.2% Statements 25/29
37.5% Branches 3/8
66.66% Functions 8/12
84.61% Lines 22/26

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 9366x         66x             66x                               3860x 3860x 3860x 3860x   3860x 3860x                       1095x               786x       1912x               1968x 1968x 1968x 1968x                 60x 60x 60x 60x       1x       1x      
import { constants } from '../constants';
import { Buffer } from '../internal/buffer';
import type { Link } from './Link';
import type { Node } from './Node';
 
const { O_APPEND } = constants;
 
/**
 * Represents an open file (file descriptor) that points to a `Link` (Hard-link) and a `Node`.
 *
 * @todo Rename to `OpenFile`.
 */
export class File {
  /**
   * A cursor/offset position in a file, where data will be written on write.
   * User can "seek" this position.
   */
  position: number;
 
  /**
   * Open a Link-Node pair. `node` is provided separately as that might be a different node
   * rather the one `link` points to, because it might be a symlink.
   * @param link
   * @param node
   * @param flags
   * @param fd
   */
  constructor(
    public readonly link: Link,
    public readonly node: Node,
    public flags: number,
    public fd: number,
  ) {
    this.position = 0;
    if (this.flags & O_APPEND) this.position = this.getSize();
  }
 
  getString(encoding = 'utf8'): string {
    return this.node.getString();
  }
 
  setString(str: string) {
    this.node.setString(str);
  }
 
  getBuffer(): Buffer {
    return this.node.getBuffer();
  }
 
  setBuffer(buf: Buffer) {
    this.node.setBuffer(buf);
  }
 
  getSize(): number {
    return this.node.getSize();
  }
 
  truncate(len?: number) {
    this.node.truncate(len);
  }
 
  seekTo(position: number) {
    this.position = position;
  }
 
  write(buf: Buffer, offset: number = 0, length: number = buf.length, position?: number | null): number {
    if (typeof position !== 'number') position = this.position;
    const bytes = this.node.write(buf, offset, length, position);
    this.position = position + bytes;
    return bytes;
  }
 
  read(
    buf: Buffer | ArrayBufferView | DataView,
    offset: number = 0,
    length: number = buf.byteLength,
    position?: number,
  ): number {
    if (typeof position !== 'number') position = this.position;
    const bytes = this.node.read(buf, offset, length, position);
    this.position = position + bytes;
    return bytes;
  }
 
  chmod(perm: number) {
    this.node.chmod(perm);
  }
 
  chown(uid: number, gid: number) {
    this.node.chown(uid, gid);
  }
}