MCPcopy Index your code
hub / github.com/nodejs/node / readFileSync

Function readFileSync

lib/fs.js:524–607  ·  view source on GitHub ↗

* 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)

Source from the content-addressed store, hash-verified

522 * @returns {string | Buffer}
523 */
524function 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 {

Calls 15

isInt32Function · 0.85
stringToFlagsFunction · 0.85
tryStatSyncFunction · 0.85
isFileTypeFunction · 0.85
tryGetReadFileBufferFunction · 0.85
tryCreateBufferFunction · 0.85
tryReadSyncFunction · 0.85
concatMethod · 0.80
sliceMethod · 0.65
getOptionsFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…