All files / lib/internal/fs promises.js

99.12% Statements 791/798
96.52% Branches 194/201
100% Functions 63/63
99.12% Lines 791/798

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 471x 471x 471x 471x 471x 471x 471x 143x 143x 2x 2x 143x 143x 921x 921x 143x 143x 2x 2x 143x 143x 3x 3x 143x 143x 2x 2x 143x 143x 2x 2x 143x 143x 2x 2x 143x 143x 26x 26x 143x 143x 4x 4x 143x 143x 8x 8x 143x 143x 8x 8x 143x 143x 2x 2x 143x 143x 1x 1x 143x 143x 15x 15x 143x 143x 4x 4x 143x 143x 2x 2x 143x 143x 462x 8x 8x 454x 462x     454x 454x 458x 450x 450x 450x 450x 450x 462x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 454x 454x 454x 462x 143x 143x 7x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 7x 143x 143x 9x 9x 143x 143x 2x 2x 2x 143x 143x 89x 89x 143x 143x 89x 89x 4x 4x 4x 4x 4x 4x 4x 89x 143x 143x 397x 397x 397x 397x 397x 17x 17x 17x 17x 17x 397x 397x 143x 81x 81x 81x 81x 81x 2x 2x 2x 2x 2x 2x 78x 78x 78x 78x 78x 78x 78x 81x 143x 1588x 1588x 1588x 1588x 143x 54x 54x 54x 14x 24x 24x 24x 24x 24x 27x 27x 27x 27x 27x 27x 24x 6x 6x 38x 38x 54x 36x 37x 37x 37x 37x 34x 34x 34x 34x 34x 34x 54x 54x 143x 353x 353x 353x 353x 353x 353x 347x 347x 347x 347x 348x 345x 349x     345x 345x 349x 344x 344x 344x 344x 344x 353x 353x 347x 347x 347x 347x 347x 7x 7x 7x 347x 340x 340x 340x 340x 347x 347x 347x 347x 347x 347x 2x 2x 2x 2x 349x 344x 344x 349x 339x 349x 5x 5x 5x 344x 353x 353x 143x 143x 143x 22x 22x 22x 22x 22x 22x 22x 143x 13x 13x 13x 13x 13x 13x 13x 13x 13x 143x 143x 143x 486x 486x 486x 486x 486x 486x 486x 486x 143x 26x 26x 26x 5x 1x 1x 5x 3x 3x 5x 2x 2x 5x 5x 5x 5x 26x 26x 1x 26x 25x 25x 26x 26x 26x 26x 26x 25x 26x 1x 1x 1x 24x 24x 24x 24x 25x 24x 24x 26x 26x 26x 26x 143x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 143x 78x 78x 78x 77x 78x 71x 3x 71x 68x 68x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 6x 6x 6x 6x 78x 78x 78x 143x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 143x 1x 1x 1x 1x 1x 1x 1x 143x 5x 5x 5x 5x 143x 7x 7x 7x 7x 7x 143x 7x 7x 7x 3x 7x 143x 10x 10x 10x 10x 10x 4x 4x 2x 1x 1x 4x 7x 7x 10x 143x 2x 2x 2x 143x 2x 2x 2x 143x 20x 20x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 143x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 143x 1x 1x 1x 1x 1x 1x 143x 2x 2x 2x 2x 2x 2x 2x 2x 2x 143x 6x 6x 6x 6x 143x 4x 4x 4x 4x 4x 4x 143x 124x 124x 124x 124x 107x 124x 143x 1x 1x 1x 1x 1x 1x 1x 143x 9x 9x 9x 9x 143x 3x 3x 3x 3x 143x 2x 2x 2x 2x 2x 143x 1x 1x 1x       1x 143x 20x 20x 20x 20x 20x 20x 20x 143x 2x 2x 2x 2x 2x 143x 2x 2x 2x 2x 2x 2x 2x 143x 1x 1x 1x 1x 1x 1x 1x 143x 1x 1x 1x 1x 1x 143x 1x 1x 1x 1x 1x 1x 1x 143x 1x 1x 1x 1x 1x 143x 2x 2x 2x 1x 1x 1x 1x 1x 2x 143x 67x 67x 67x 67x 67x 38x 38x 38x 54x 54x 54x 67x 48x 48x 48x 48x 48x 48x 67x 143x 105x 105x 105x 143x 10x 10x 10x 10x 10x 10x 143x 361x 361x 361x 361x 361x 361x 351x 351x 351x 351x 344x 361x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x 143x  
'use strict';
 
const {
  ArrayPrototypePush,
  Error,
  MathMax,
  MathMin,
  NumberIsSafeInteger,
  Promise,
  PromisePrototypeThen,
  PromiseResolve,
  PromiseReject,
  SafeArrayIterator,
  SafePromisePrototypeFinally,
  Symbol,
  Uint8Array,
} = primordials;
 
const {
  F_OK,
  O_SYMLINK,
  O_WRONLY,
  S_IFMT,
  S_IFREG
} = internalBinding('constants').fs;
const binding = internalBinding('fs');
const { Buffer } = require('buffer');
 
const {
  codes: {
    ERR_FS_FILE_TOO_LARGE,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_METHOD_NOT_IMPLEMENTED,
  },
  AbortError,
  aggregateTwoErrors,
} = require('internal/errors');
const { isArrayBufferView } = require('internal/util/types');
const { rimrafPromises } = require('internal/fs/rimraf');
const {
  constants: {
    kIoMaxLength,
    kMaxUserId,
    kReadFileBufferLength,
    kReadFileUnknownBufferLength,
    kWriteFileMaxChunkSize,
  },
  copyObject,
  emitRecursiveRmdirWarning,
  getDirents,
  getOptions,
  getStatsFromBinding,
  getValidatedPath,
  getValidMode,
  nullCheck,
  preprocessSymlinkDestination,
  stringToFlags,
  stringToSymlinkType,
  toUnixTimestamp,
  validateBufferArray,
  validateOffsetLengthRead,
  validateOffsetLengthWrite,
  validateRmOptions,
  validateRmdirOptions,
  validateStringAfterArrayBufferView,
  warnOnNonPortableTemplate
} = require('internal/fs/utils');
const { opendir } = require('internal/fs/dir');
const {
  parseFileMode,
  validateAbortSignal,
  validateBoolean,
  validateBuffer,
  validateEncoding,
  validateInteger,
} = require('internal/validators');
const pathModule = require('path');
const { promisify } = require('internal/util');
const { EventEmitterMixin } = require('internal/event_target');
const { watch } = require('internal/fs/watchers');
const { isIterable } = require('internal/streams/utils');
const assert = require('internal/assert');
 
const kHandle = Symbol('kHandle');
const kFd = Symbol('kFd');
const kRefs = Symbol('kRefs');
const kClosePromise = Symbol('kClosePromise');
const kCloseResolve = Symbol('kCloseResolve');
const kCloseReject = Symbol('kCloseReject');
const kRef = Symbol('kRef');
const kUnref = Symbol('kUnref');
 
const { kUsePromises } = binding;
const {
  JSTransferable, kDeserialize, kTransfer, kTransferList
} = require('internal/worker/js_transferable');
 
const getDirectoryEntriesPromise = promisify(getDirents);
const validateRmOptionsPromise = promisify(validateRmOptions);
 
class FileHandle extends EventEmitterMixin(JSTransferable) {
  /**
   * @param {InternalFSBinding.FileHandle | undefined} filehandle
   */
  constructor(filehandle) {
    super();
    this[kHandle] = filehandle;
    this[kFd] = filehandle ? filehandle.fd : -1;
 
    this[kRefs] = 1;
    this[kClosePromise] = null;
  }
 
  getAsyncId() {
    return this[kHandle].getAsyncId();
  }
 
  get fd() {
    return this[kFd];
  }
 
  appendFile(data, options) {
    return fsCall(writeFile, this, data, options);
  }
 
  chmod(mode) {
    return fsCall(fchmod, this, mode);
  }
 
  chown(uid, gid) {
    return fsCall(fchown, this, uid, gid);
  }
 
  datasync() {
    return fsCall(fdatasync, this);
  }
 
  sync() {
    return fsCall(fsync, this);
  }
 
  read(buffer, offset, length, position) {
    return fsCall(read, this, buffer, offset, length, position);
  }
 
  readv(buffers, position) {
    return fsCall(readv, this, buffers, position);
  }
 
  readFile(options) {
    return fsCall(readFile, this, options);
  }
 
  stat(options) {
    return fsCall(fstat, this, options);
  }
 
  truncate(len = 0) {
    return fsCall(ftruncate, this, len);
  }
 
  utimes(atime, mtime) {
    return fsCall(futimes, this, atime, mtime);
  }
 
  write(buffer, offset, length, position) {
    return fsCall(write, this, buffer, offset, length, position);
  }
 
  writev(buffers, position) {
    return fsCall(writev, this, buffers, position);
  }
 
  writeFile(data, options) {
    return fsCall(writeFile, this, data, options);
  }
 
  close = () => {
    if (this[kFd] === -1) {
      return PromiseResolve();
    }
 
    if (this[kClosePromise]) {
      return this[kClosePromise];
    }
 
    this[kRefs]--;
    if (this[kRefs] === 0) {
      this[kFd] = -1;
      this[kClosePromise] = SafePromisePrototypeFinally(
        this[kHandle].close(),
        () => { this[kClosePromise] = undefined; }
      );
    } else {
      this[kClosePromise] = SafePromisePrototypeFinally(
        new Promise((resolve, reject) => {
          this[kCloseResolve] = resolve;
          this[kCloseReject] = reject;
        }), () => {
          this[kClosePromise] = undefined;
          this[kCloseReject] = undefined;
          this[kCloseResolve] = undefined;
        }
      );
    }
 
    this.emit('close');
    return this[kClosePromise];
  }
 
  [kTransfer]() {
    if (this[kClosePromise] || this[kRefs] > 1) {
      const DOMException = internalBinding('messaging').DOMException;
      throw new DOMException('Cannot transfer FileHandle while in use',
                             'DataCloneError');
    }
 
    const handle = this[kHandle];
    this[kFd] = -1;
    this[kHandle] = null;
    this[kRefs] = 0;
 
    return {
      data: { handle },
      deserializeInfo: 'internal/fs/promises:FileHandle'
    };
  }
 
  [kTransferList]() {
    return [ this[kHandle] ];
  }
 
  [kDeserialize]({ handle }) {
    this[kHandle] = handle;
    this[kFd] = handle.fd;
  }
 
  [kRef]() {
    this[kRefs]++;
  }
 
  [kUnref]() {
    this[kRefs]--;
    if (this[kRefs] === 0) {
      this[kFd] = -1;
      PromisePrototypeThen(
        this[kHandle].close(),
        this[kCloseResolve],
        this[kCloseReject]
      );
    }
  }
}
 
async function handleFdClose(fileOpPromise, closeFunc) {
  return PromisePrototypeThen(
    fileOpPromise,
    (result) => PromisePrototypeThen(closeFunc(), () => result),
    (opError) =>
      PromisePrototypeThen(
        closeFunc(),
        () => PromiseReject(opError),
        (closeError) => PromiseReject(aggregateTwoErrors(closeError, opError))
      )
  );
}
 
async function fsCall(fn, handle, ...args) {
  assert(handle[kRefs] !== undefined,
         'handle must be an instance of FileHandle');
 
  if (handle.fd === -1) {
    // eslint-disable-next-line no-restricted-syntax
    const err = new Error('file closed');
    err.code = 'EBADF';
    err.syscall = fn.name;
    throw err;
  }
 
  try {
    handle[kRef]();
    return await fn(handle, ...new SafeArrayIterator(args));
  } finally {
    handle[kUnref]();
  }
}
 
function checkAborted(signal) {
  if (signal?.aborted)
    throw new AbortError();
}
 
async function writeFileHandle(filehandle, data, signal, encoding) {
  checkAborted(signal);
  if (isCustomIterable(data)) {
    for await (const buf of data) {
      checkAborted(signal);
      const toWrite =
        isArrayBufferView(buf) ? buf : Buffer.from(buf, encoding || 'utf8');
      let remaining = toWrite.byteLength;
      while (remaining > 0) {
        const writeSize = MathMin(kWriteFileMaxChunkSize, remaining);
        const { bytesWritten } = await write(
          filehandle, toWrite, toWrite.byteLength - remaining, writeSize);
        remaining -= bytesWritten;
        checkAborted(signal);
      }
    }
    return;
  }
  data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  let remaining = data.byteLength;
  if (remaining === 0) return;
  do {
    checkAborted(signal);
    const { bytesWritten } =
      await write(filehandle, data, 0,
                  MathMin(kWriteFileMaxChunkSize, data.byteLength));
    remaining -= bytesWritten;
    data = new Uint8Array(
      data.buffer,
      data.byteOffset + bytesWritten,
      data.byteLength - bytesWritten
    );
  } while (remaining > 0);
}
 
async function readFileHandle(filehandle, options) {
  const signal = options?.signal;
 
  checkAborted(signal);
 
  const statFields = await binding.fstat(filehandle.fd, false, kUsePromises);
 
  checkAborted(signal);
 
  let size;
  if ((statFields[1/* mode */] & S_IFMT) === S_IFREG) {
    size = statFields[8/* size */];
  } else {
    size = 0;
  }
 
  if (size > kIoMaxLength)
    throw new ERR_FS_FILE_TOO_LARGE(size);
 
  let endOfFile = false;
  let totalRead = 0;
  const noSize = size === 0;
  const buffers = [];
  const fullBuffer = noSize ? undefined : Buffer.allocUnsafeSlow(size);
  do {
    checkAborted(signal);
    let buffer;
    let offset;
    let length;
    if (noSize) {
      buffer = Buffer.allocUnsafeSlow(kReadFileUnknownBufferLength);
      offset = 0;
      length = kReadFileUnknownBufferLength;
    } else {
      buffer = fullBuffer;
      offset = totalRead;
      length = MathMin(size - totalRead, kReadFileBufferLength);
    }
 
    const bytesRead = (await binding.read(filehandle.fd, buffer, offset,
                                          length, -1, kUsePromises)) || 0;
    totalRead += bytesRead;
    endOfFile = bytesRead === 0 || totalRead === size;
    if (noSize && bytesRead > 0) {
      const isBufferFull = bytesRead === kReadFileUnknownBufferLength;
      const chunkBuffer = isBufferFull ? buffer : buffer.slice(0, bytesRead);
      ArrayPrototypePush(buffers, chunkBuffer);
    }
  } while (!endOfFile);
 
  let result;
  if (size > 0) {
    result = totalRead === size ? fullBuffer : fullBuffer.slice(0, totalRead);
  } else {
    result = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers,
                                                               totalRead);
  }
 
  return options.encoding ? result.toString(options.encoding) : result;
}
 
// All of the functions are defined as async in order to ensure that errors
// thrown cause promise rejections rather than being thrown synchronously.
async function access(path, mode = F_OK) {
  path = getValidatedPath(path);
 
  mode = getValidMode(mode, 'access');
  return binding.access(pathModule.toNamespacedPath(path), mode,
                        kUsePromises);
}
 
async function copyFile(src, dest, mode) {
  src = getValidatedPath(src, 'src');
  dest = getValidatedPath(dest, 'dest');
  mode = getValidMode(mode, 'copyFile');
  return binding.copyFile(pathModule.toNamespacedPath(src),
                          pathModule.toNamespacedPath(dest),
                          mode,
                          kUsePromises);
}
 
// Note that unlike fs.open() which uses numeric file descriptors,
// fsPromises.open() uses the fs.FileHandle class.
async function open(path, flags, mode) {
  path = getValidatedPath(path);
  const flagsNumber = stringToFlags(flags);
  mode = parseFileMode(mode, 'mode', 0o666);
  return new FileHandle(
    await binding.openFileHandle(pathModule.toNamespacedPath(path),
                                 flagsNumber, mode, kUsePromises));
}
 
async function read(handle, bufferOrOptions, offset, length, position) {
  let buffer = bufferOrOptions;
  if (!isArrayBufferView(buffer)) {
    if (bufferOrOptions === undefined) {
      bufferOrOptions = {};
    }
    if (bufferOrOptions.buffer) {
      buffer = bufferOrOptions.buffer;
      validateBuffer(buffer);
    } else {
      buffer = Buffer.alloc(16384);
    }
    offset = bufferOrOptions.offset || 0;
    length = buffer.byteLength;
    position = bufferOrOptions.position || null;
  }
 
  if (offset == null) {
    offset = 0;
  } else {
    validateInteger(offset, 'offset', 0);
  }
 
  length |= 0;
 
  if (length === 0)
    return { bytesRead: length, buffer };
 
  if (buffer.byteLength === 0) {
    throw new ERR_INVALID_ARG_VALUE('buffer', buffer,
                                    'is empty and cannot be written');
  }
 
  validateOffsetLengthRead(offset, length, buffer.byteLength);
 
  if (!NumberIsSafeInteger(position))
    position = -1;
 
  const bytesRead = (await binding.read(handle.fd, buffer, offset, length,
                                        position, kUsePromises)) || 0;
 
  return { bytesRead, buffer };
}
 
async function readv(handle, buffers, position) {
  validateBufferArray(buffers);
 
  if (typeof position !== 'number')
    position = null;
 
  const bytesRead = (await binding.readBuffers(handle.fd, buffers, position,
                                               kUsePromises)) || 0;
  return { bytesRead, buffers };
}
 
async function write(handle, buffer, offset, length, position) {
  if (buffer?.byteLength === 0)
    return { bytesWritten: 0, buffer };
 
  if (isArrayBufferView(buffer)) {
    if (offset == null) {
      offset = 0;
    } else {
      validateInteger(offset, 'offset', 0);
    }
    if (typeof length !== 'number')
      length = buffer.byteLength - offset;
    if (typeof position !== 'number')
      position = null;
    validateOffsetLengthWrite(offset, length, buffer.byteLength);
    const bytesWritten =
      (await binding.writeBuffer(handle.fd, buffer, offset,
                                 length, position, kUsePromises)) || 0;
    return { bytesWritten, buffer };
  }
 
  validateStringAfterArrayBufferView(buffer, 'buffer');
  validateEncoding(buffer, length);
  const bytesWritten = (await binding.writeString(handle.fd, buffer, offset,
                                                  length, kUsePromises)) || 0;
  return { bytesWritten, buffer };
}
 
async function writev(handle, buffers, position) {
  validateBufferArray(buffers);
 
  if (typeof position !== 'number')
    position = null;
 
  const bytesWritten = (await binding.writeBuffers(handle.fd, buffers, position,
                                                   kUsePromises)) || 0;
  return { bytesWritten, buffers };
}
 
async function rename(oldPath, newPath) {
  oldPath = getValidatedPath(oldPath, 'oldPath');
  newPath = getValidatedPath(newPath, 'newPath');
  return binding.rename(pathModule.toNamespacedPath(oldPath),
                        pathModule.toNamespacedPath(newPath),
                        kUsePromises);
}
 
async function truncate(path, len = 0) {
  const fd = await open(path, 'r+');
  return handleFdClose(ftruncate(fd, len), fd.close);
}
 
async function ftruncate(handle, len = 0) {
  validateInteger(len, 'len');
  len = MathMax(0, len);
  return binding.ftruncate(handle.fd, len, kUsePromises);
}
 
async function rm(path, options) {
  path = pathModule.toNamespacedPath(getValidatedPath(path));
  options = await validateRmOptionsPromise(path, options, false);
  return rimrafPromises(path, options);
}
 
async function rmdir(path, options) {
  path = pathModule.toNamespacedPath(getValidatedPath(path));
  options = validateRmdirOptions(options);
 
  if (options.recursive) {
    emitRecursiveRmdirWarning();
    const stats = await stat(path);
    if (stats.isDirectory()) {
      return rimrafPromises(path, options);
    }
  }
 
  return binding.rmdir(path, kUsePromises);
}
 
async function fdatasync(handle) {
  return binding.fdatasync(handle.fd, kUsePromises);
}
 
async function fsync(handle) {
  return binding.fsync(handle.fd, kUsePromises);
}
 
async function mkdir(path, options) {
  if (typeof options === 'number' || typeof options === 'string') {
    options = { mode: options };
  }
  const {
    recursive = false,
    mode = 0o777
  } = options || {};
  path = getValidatedPath(path);
  validateBoolean(recursive, 'options.recursive');
 
  return binding.mkdir(pathModule.toNamespacedPath(path),
                       parseFileMode(mode, 'mode', 0o777), recursive,
                       kUsePromises);
}
 
async function readdir(path, options) {
  options = getOptions(options, {});
  path = getValidatedPath(path);
  const result = await binding.readdir(pathModule.toNamespacedPath(path),
                                       options.encoding,
                                       !!options.withFileTypes,
                                       kUsePromises);
  return options.withFileTypes ?
    getDirectoryEntriesPromise(path, result) :
    result;
}
 
async function readlink(path, options) {
  options = getOptions(options, {});
  path = getValidatedPath(path, 'oldPath');
  return binding.readlink(pathModule.toNamespacedPath(path),
                          options.encoding, kUsePromises);
}
 
async function symlink(target, path, type_) {
  const type = (typeof type_ === 'string' ? type_ : null);
  target = getValidatedPath(target, 'target');
  path = getValidatedPath(path);
  return binding.symlink(preprocessSymlinkDestination(target, type, path),
                         pathModule.toNamespacedPath(path),
                         stringToSymlinkType(type),
                         kUsePromises);
}
 
async function fstat(handle, options = { bigint: false }) {
  const result = await binding.fstat(handle.fd, options.bigint, kUsePromises);
  return getStatsFromBinding(result);
}
 
async function lstat(path, options = { bigint: false }) {
  path = getValidatedPath(path);
  const result = await binding.lstat(pathModule.toNamespacedPath(path),
                                     options.bigint, kUsePromises);
  return getStatsFromBinding(result);
}
 
async function stat(path, options = { bigint: false }) {
  path = getValidatedPath(path);
  const result = await binding.stat(pathModule.toNamespacedPath(path),
                                    options.bigint, kUsePromises);
  return getStatsFromBinding(result);
}
 
async function link(existingPath, newPath) {
  existingPath = getValidatedPath(existingPath, 'existingPath');
  newPath = getValidatedPath(newPath, 'newPath');
  return binding.link(pathModule.toNamespacedPath(existingPath),
                      pathModule.toNamespacedPath(newPath),
                      kUsePromises);
}
 
async function unlink(path) {
  path = getValidatedPath(path);
  return binding.unlink(pathModule.toNamespacedPath(path), kUsePromises);
}
 
async function fchmod(handle, mode) {
  mode = parseFileMode(mode, 'mode');
  return binding.fchmod(handle.fd, mode, kUsePromises);
}
 
async function chmod(path, mode) {
  path = getValidatedPath(path);
  mode = parseFileMode(mode, 'mode');
  return binding.chmod(pathModule.toNamespacedPath(path), mode, kUsePromises);
}
 
async function lchmod(path, mode) {
  if (O_SYMLINK === undefined)
    throw new ERR_METHOD_NOT_IMPLEMENTED('lchmod()');

  const fd = await open(path, O_WRONLY | O_SYMLINK);
  return handleFdClose(fchmod(fd, mode), fd.close);
}
 
async function lchown(path, uid, gid) {
  path = getValidatedPath(path);
  validateInteger(uid, 'uid', -1, kMaxUserId);
  validateInteger(gid, 'gid', -1, kMaxUserId);
  return binding.lchown(pathModule.toNamespacedPath(path),
                        uid, gid, kUsePromises);
}
 
async function fchown(handle, uid, gid) {
  validateInteger(uid, 'uid', -1, kMaxUserId);
  validateInteger(gid, 'gid', -1, kMaxUserId);
  return binding.fchown(handle.fd, uid, gid, kUsePromises);
}
 
async function chown(path, uid, gid) {
  path = getValidatedPath(path);
  validateInteger(uid, 'uid', -1, kMaxUserId);
  validateInteger(gid, 'gid', -1, kMaxUserId);
  return binding.chown(pathModule.toNamespacedPath(path),
                       uid, gid, kUsePromises);
}
 
async function utimes(path, atime, mtime) {
  path = getValidatedPath(path);
  return binding.utimes(pathModule.toNamespacedPath(path),
                        toUnixTimestamp(atime),
                        toUnixTimestamp(mtime),
                        kUsePromises);
}
 
async function futimes(handle, atime, mtime) {
  atime = toUnixTimestamp(atime, 'atime');
  mtime = toUnixTimestamp(mtime, 'mtime');
  return binding.futimes(handle.fd, atime, mtime, kUsePromises);
}
 
async function lutimes(path, atime, mtime) {
  path = getValidatedPath(path);
  return binding.lutimes(pathModule.toNamespacedPath(path),
                         toUnixTimestamp(atime),
                         toUnixTimestamp(mtime),
                         kUsePromises);
}
 
async function realpath(path, options) {
  options = getOptions(options, {});
  path = getValidatedPath(path);
  return binding.realpath(path, options.encoding, kUsePromises);
}
 
async function mkdtemp(prefix, options) {
  options = getOptions(options, {});
  if (!prefix || typeof prefix !== 'string') {
    throw new ERR_INVALID_ARG_TYPE('prefix', 'string', prefix);
  }
  nullCheck(prefix);
  warnOnNonPortableTemplate(prefix);
  return binding.mkdtemp(`${prefix}XXXXXX`, options.encoding, kUsePromises);
}
 
async function writeFile(path, data, options) {
  options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
  const flag = options.flag || 'w';
 
  if (!isArrayBufferView(data) && !isCustomIterable(data)) {
    validateStringAfterArrayBufferView(data, 'data');
    data = Buffer.from(data, options.encoding || 'utf8');
  }
 
  validateAbortSignal(options.signal);
  if (path instanceof FileHandle)
    return writeFileHandle(path, data, options.signal, options.encoding);
 
  checkAborted(options.signal);
 
  const fd = await open(path, flag, options.mode);
  return handleFdClose(
    writeFileHandle(fd, data, options.signal, options.encoding), fd.close);
}
 
function isCustomIterable(obj) {
  return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
 
async function appendFile(path, data, options) {
  options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
  options = copyObject(options);
  options.flag = options.flag || 'a';
  return writeFile(path, data, options);
}
 
async function readFile(path, options) {
  options = getOptions(options, { flag: 'r' });
  const flag = options.flag || 'r';
 
  if (path instanceof FileHandle)
    return readFileHandle(path, options);
 
  checkAborted(options.signal);
 
  const fd = await open(path, flag, 0o666);
  return handleFdClose(readFileHandle(fd, options), fd.close);
}
 
module.exports = {
  exports: {
    access,
    copyFile,
    open,
    opendir: promisify(opendir),
    rename,
    truncate,
    rm,
    rmdir,
    mkdir,
    readdir,
    readlink,
    symlink,
    lstat,
    stat,
    link,
    unlink,
    chmod,
    lchmod,
    lchown,
    chown,
    utimes,
    lutimes,
    realpath,
    mkdtemp,
    writeFile,
    appendFile,
    readFile,
    watch,
  },
 
  FileHandle,
  kRef,
  kUnref,
};