* 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)
| 2887 | * @returns {void} |
| 2888 | */ |
| 2889 | function 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 |
no test coverage detected
searching dependent graphs…