* Synchronously reads the entire contents of a file. * @param {string | Buffer | URL | number} path * @param {{ * encoding?: string | null; * flag?: string; * }} [options] * @returns {string | Buffer}
(path, options)
| 522 | * @returns {string | Buffer} |
| 523 | */ |
| 524 | function readFileSync(path, options) { |
| 525 | const h = vfsState.handlers; |
| 526 | if (h !== null) { |
| 527 | const result = h.readFileSync(path, options); |
| 528 | if (result !== undefined) return result; |
| 529 | } |
| 530 | options = getOptions(options, { flag: 'r' }); |
| 531 | validateReadFileBufferOptions(options); |
| 532 | const hasUserBuffer = options.buffer !== undefined; |
| 533 | |
| 534 | if ((options.encoding === 'utf8' || options.encoding === 'utf-8') && |
| 535 | !hasUserBuffer) { |
| 536 | if (!isInt32(path)) { |
| 537 | path = getValidatedPath(path); |
| 538 | } |
| 539 | return binding.readFileUtf8(path, stringToFlags(options.flag)); |
| 540 | } |
| 541 | |
| 542 | const isUserFd = isFd(path); // File descriptor ownership |
| 543 | const fd = isUserFd ? path : fs.openSync(path, options.flag, 0o666); |
| 544 | |
| 545 | const stats = tryStatSync(fd, isUserFd); |
| 546 | const size = isFileType(stats, S_IFREG) ? stats[8] : 0; |
| 547 | let pos = 0; |
| 548 | let buffer; // Single buffer with file data |
| 549 | let buffers; // List for when size is unknown |
| 550 | |
| 551 | if (hasUserBuffer) { |
| 552 | buffer = tryGetReadFileBuffer(options, size, fd, isUserFd); |
| 553 | } else if (size === 0) { |
| 554 | buffers = []; |
| 555 | } else { |
| 556 | buffer = tryCreateBuffer(size, fd, isUserFd); |
| 557 | } |
| 558 | |
| 559 | let bytesRead; |
| 560 | |
| 561 | if (hasUserBuffer) { |
| 562 | if (size !== 0) { |
| 563 | do { |
| 564 | bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos); |
| 565 | pos += bytesRead; |
| 566 | } while (bytesRead !== 0 && pos < size); |
| 567 | } else { |
| 568 | pos = tryReadSyncWithUserBuffer( |
| 569 | fd, |
| 570 | isUserFd, |
| 571 | buffer, |
| 572 | getReadFileBufferByteLengthName(options), |
| 573 | ); |
| 574 | } |
| 575 | } else if (size !== 0) { |
| 576 | do { |
| 577 | bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos); |
| 578 | pos += bytesRead; |
| 579 | } while (bytesRead !== 0 && pos < size); |
| 580 | } else { |
| 581 | do { |
no test coverage detected
searching dependent graphs…