diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index c78eb4f2346b05..c84a3516476293 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import { pathToFileURL } from 'node:url' import { performance } from 'node:perf_hooks' @@ -1085,12 +1086,12 @@ async function loadConfigFromBundledFile( .slice(2)})}` const fileNameTmp = `${fileBase}.mjs` const fileUrl = `${pathToFileURL(fileBase)}.mjs` - fs.writeFileSync(fileNameTmp, bundledCode) + await fsp.writeFile(fileNameTmp, bundledCode) try { return (await dynamicImport(fileUrl)).default } finally { try { - fs.unlinkSync(fileNameTmp) + await fsp.unlink(fileNameTmp) } catch { // already removed if this function is called twice simultaneously } @@ -1099,7 +1100,7 @@ async function loadConfigFromBundledFile( // for cjs, we can register a custom loader via `_require.extensions` else { const extension = path.extname(fileName) - const realFileName = fs.realpathSync(fileName) + const realFileName = await fsp.realpath(fileName) const loaderExt = extension in _require.extensions ? extension : '.js' const defaultLoader = _require.extensions[loaderExt]! _require.extensions[loaderExt] = (module: NodeModule, filename: string) => { diff --git a/packages/vite/src/node/http.ts b/packages/vite/src/node/http.ts index 7af73c899cccb2..88ccd4b955cdbc 100644 --- a/packages/vite/src/node/http.ts +++ b/packages/vite/src/node/http.ts @@ -1,4 +1,4 @@ -import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import type { Server as HttpServer, @@ -124,23 +124,21 @@ export async function resolveHttpsConfig( https: boolean | HttpsServerOptions | undefined, ): Promise { if (!https) return undefined + if (!isObject(https)) return {} - const httpsOption = isObject(https) ? { ...https } : {} - - const { ca, cert, key, pfx } = httpsOption - Object.assign(httpsOption, { - ca: readFileIfExists(ca), - cert: readFileIfExists(cert), - key: readFileIfExists(key), - pfx: readFileIfExists(pfx), - }) - return httpsOption + const [ca, cert, key, pfx] = await Promise.all([ + readFileIfExists(https.ca), + readFileIfExists(https.cert), + readFileIfExists(https.key), + readFileIfExists(https.pfx), + ]) + return { ...https, ca, cert, key, pfx } } -function readFileIfExists(value?: string | Buffer | any[]) { +async function readFileIfExists(value?: string | Buffer | any[]) { if (typeof value === 'string') { try { - return fs.readFileSync(path.resolve(value)) + return fsp.readFile(path.resolve(value)) } catch (e) { return value } diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index c9e189a5da18e6..580a6c8ceefba6 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -233,7 +233,7 @@ export async function optimizeDeps( const ssr = config.command === 'build' && !!config.build.ssr - const cachedMetadata = loadCachedDepOptimizationMetadata( + const cachedMetadata = await loadCachedDepOptimizationMetadata( config, ssr, force, @@ -263,7 +263,7 @@ export async function optimizeServerSsrDeps( config: ResolvedConfig, ): Promise { const ssr = true - const cachedMetadata = loadCachedDepOptimizationMetadata( + const cachedMetadata = await loadCachedDepOptimizationMetadata( config, ssr, config.optimizeDeps.force, @@ -340,12 +340,12 @@ export function addOptimizedDepInfo( * Creates the initial dep optimization metadata, loading it from the deps cache * if it exists and pre-bundling isn't forced */ -export function loadCachedDepOptimizationMetadata( +export async function loadCachedDepOptimizationMetadata( config: ResolvedConfig, ssr: boolean, force = config.optimizeDeps.force, asCommand = false, -): DepOptimizationMetadata | undefined { +): Promise { const log = asCommand ? config.logger.info : debug // Before Vite 2.9, dependencies were cached in the root of the cacheDir @@ -361,7 +361,7 @@ export function loadCachedDepOptimizationMetadata( try { const cachedMetadataPath = path.join(depsCacheDir, '_metadata.json') cachedMetadata = parseDepsOptimizerMetadata( - fs.readFileSync(cachedMetadataPath, 'utf-8'), + await fsp.readFile(cachedMetadataPath, 'utf-8'), depsCacheDir, ) } catch (e) {} @@ -377,7 +377,7 @@ export function loadCachedDepOptimizationMetadata( } // Start with a fresh cache - fs.rmSync(depsCacheDir, { recursive: true, force: true }) + await fsp.rm(depsCacheDir, { recursive: true, force: true }) } /** @@ -508,7 +508,11 @@ export function runOptimizeDeps( const cleanUp = () => { if (!cleaned) { cleaned = true - fs.rmSync(processingCacheDir, { recursive: true, force: true }) + // No need to wait, we can clean up in the background because temp folders + // are unique per run + fsp.rm(processingCacheDir, { recursive: true, force: true }).catch(() => { + // Ignore errors + }) } } const createProcessingResult = () => ({ @@ -1114,7 +1118,7 @@ export async function extractExportsData( let parseResult: ReturnType let usedJsxLoader = false - const entryContent = fs.readFileSync(filePath, 'utf-8') + const entryContent = await fsp.readFile(filePath, 'utf-8') try { parseResult = parse(entryContent) } catch { diff --git a/packages/vite/src/node/optimizer/optimizer.ts b/packages/vite/src/node/optimizer/optimizer.ts index 629f8b9b9ccd3a..9e016310709f8c 100644 --- a/packages/vite/src/node/optimizer/optimizer.ts +++ b/packages/vite/src/node/optimizer/optimizer.ts @@ -99,7 +99,7 @@ async function createDepsOptimizer( const sessionTimestamp = Date.now().toString() - const cachedMetadata = loadCachedDepOptimizationMetadata(config, ssr) + const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr) let handle: NodeJS.Timeout | undefined diff --git a/packages/vite/src/node/optimizer/scan.ts b/packages/vite/src/node/optimizer/scan.ts index 7929b337b8a6e4..32f9b2b1f4b979 100644 --- a/packages/vite/src/node/optimizer/scan.ts +++ b/packages/vite/src/node/optimizer/scan.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import { performance } from 'node:perf_hooks' import glob from 'fast-glob' @@ -363,7 +364,7 @@ function esbuildScanPlugin( build.onLoad( { filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => { - let raw = fs.readFileSync(path, 'utf-8') + let raw = await fsp.readFile(path, 'utf-8') // Avoid matching the content of the comment raw = raw.replace(commentRE, '') const isHtml = path.endsWith('.html') @@ -576,7 +577,7 @@ function esbuildScanPlugin( let ext = path.extname(id).slice(1) if (ext === 'mjs') ext = 'js' - let contents = fs.readFileSync(id, 'utf-8') + let contents = await fsp.readFile(id, 'utf-8') if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) { contents = config.esbuild.jsxInject + `\n` + contents } diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 2d1c070382b8bd..1ea8cba9c510d9 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import { createRequire } from 'node:module' import glob from 'fast-glob' @@ -1675,7 +1676,7 @@ async function rebaseUrls( return { file } } - const content = fs.readFileSync(file, 'utf-8') + const content = await fsp.readFile(file, 'utf-8') // no url() const hasUrls = cssUrlRE.test(content) // data-uri() calls @@ -1834,7 +1835,7 @@ function createViteLessPlugin( if (result && 'contents' in result) { contents = result.contents } else { - contents = fs.readFileSync(resolved, 'utf-8') + contents = await fsp.readFile(resolved, 'utf-8') } return { filename: path.resolve(resolved), diff --git a/packages/vite/src/node/server/hmr.ts b/packages/vite/src/node/server/hmr.ts index 454bccd0f83474..9e693566366c5d 100644 --- a/packages/vite/src/node/server/hmr.ts +++ b/packages/vite/src/node/server/hmr.ts @@ -1,4 +1,4 @@ -import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import type { Server } from 'node:http' import colors from 'picocolors' @@ -494,14 +494,14 @@ function error(pos: number) { // change event and sometimes this can be too early and get an empty buffer. // Poll until the file's modified time has changed before reading again. async function readModifiedFile(file: string): Promise { - const content = fs.readFileSync(file, 'utf-8') + const content = await fsp.readFile(file, 'utf-8') if (!content) { - const mtime = fs.statSync(file).mtimeMs + const mtime = (await fsp.stat(file)).mtimeMs await new Promise((r) => { let n = 0 const poll = async () => { n++ - const newMtime = fs.statSync(file).mtimeMs + const newMtime = (await fsp.stat(file)).mtimeMs if (newMtime !== mtime || n > 10) { r(0) } else { @@ -510,7 +510,7 @@ async function readModifiedFile(file: string): Promise { } setTimeout(poll, 10) }) - return fs.readFileSync(file, 'utf-8') + return await fsp.readFile(file, 'utf-8') } else { return content } diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 764f48d4ad9169..a673574fd85ed2 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import fsp from 'node:fs/promises' import path from 'node:path' import MagicString from 'magic-string' import type { SourceMapInput } from 'rollup' @@ -292,7 +293,7 @@ export function indexHtmlMiddleware( const filename = getHtmlFilename(url, server) if (fs.existsSync(filename)) { try { - let html = fs.readFileSync(filename, 'utf-8') + let html = await fsp.readFile(filename, 'utf-8') html = await server.transformIndexHtml(url, html, req.originalUrl) return send(req, res, html, 'html', { headers: server.config.server.headers,