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

Function writeFileSync

lib/fs.js:2889–2945  ·  view source on GitHub ↗

* Synchronously writes data to the file. * @param {string | Buffer | URL | number} path * @param {string | Buffer | TypedArray | DataView} data * @param {{ * encoding?: string | null; * mode?: number; * flag?: string; * flush?: boolean; * } | string} [options] * @returns {void}

(path, data, options)

Source from the content-addressed store, hash-verified

2887 * @returns {void}
2888 */
2889function writeFileSync(path, data, options) {
2890 options = getOptions(options, {
2891 encoding: 'utf8',
2892 mode: 0o666,
2893 flag: 'w',
2894 flush: false,
2895 });
2896 const flush = options.flush ?? false;
2897 validateBoolean(flush, 'options.flush');
2898 parseFileMode(options.mode, 'mode', 0o666);
2899
2900 const h = vfsState.handlers;
2901 if (h !== null) {
2902 const result = h.writeFileSync(path, data, options);
2903 if (result !== undefined) return;
2904 }
2905
2906 const flag = options.flag || 'w';
2907
2908 // C++ fast path for string data and UTF8 encoding
2909 if (typeof data === 'string' && (options.encoding === 'utf8' || options.encoding === 'utf-8')) {
2910 if (!isInt32(path)) {
2911 path = getValidatedPath(path);
2912 }
2913
2914 return binding.writeFileUtf8(
2915 path,
2916 data,
2917 stringToFlags(flag),
2918 parseFileMode(options.mode, 'mode', 0o666),
2919 );
2920 }
2921
2922 if (!isArrayBufferView(data)) {
2923 validateStringAfterArrayBufferView(data, 'data');
2924 data = Buffer.from(data, options.encoding || 'utf8');
2925 }
2926
2927 const isUserFd = isFd(path); // File descriptor ownership
2928 const fd = isUserFd ? path : fs.openSync(path, flag, options.mode);
2929
2930 let offset = 0;
2931 let length = data.byteLength;
2932 try {
2933 while (length > 0) {
2934 const written = fs.writeSync(fd, data, offset, length);
2935 offset += written;
2936 length -= written;
2937 }
2938
2939 if (flush) {
2940 fs.fsyncSync(fd);
2941 }
2942 } finally {
2943 if (!isUserFd) fs.closeSync(fd);
2944 }
2945}
2946

Calls 9

parseFileModeFunction · 0.85
isInt32Function · 0.85
stringToFlagsFunction · 0.85
getOptionsFunction · 0.50
writeFileSyncMethod · 0.45
fromMethod · 0.45
openSyncMethod · 0.45
writeSyncMethod · 0.45
closeSyncMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…