Unverified Commit 05e93e15 authored by matamatanot's avatar matamatanot Committed by GitHub

Use fs.promises instead of promisify (#12026)

parent 82596124
import crypto from 'crypto' import crypto from 'crypto'
import fs from 'fs' import { promises, writeFileSync } from 'fs'
import Worker from 'jest-worker' import Worker from 'jest-worker'
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import devalue from 'next/dist/compiled/devalue' import devalue from 'next/dist/compiled/devalue'
...@@ -8,7 +8,6 @@ import findUp from 'next/dist/compiled/find-up' ...@@ -8,7 +8,6 @@ import findUp from 'next/dist/compiled/find-up'
import nanoid from 'next/dist/compiled/nanoid/index.js' import nanoid from 'next/dist/compiled/nanoid/index.js'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import path from 'path' import path from 'path'
import { promisify } from 'util'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import checkCustomRoutes, { import checkCustomRoutes, {
getRedirectStatus, getRedirectStatus,
...@@ -73,15 +72,6 @@ import { ...@@ -73,15 +72,6 @@ import {
import getBaseWebpackConfig from './webpack-config' import getBaseWebpackConfig from './webpack-config'
import { writeBuildId } from './write-build-id' import { writeBuildId } from './write-build-id'
const fsAccess = promisify(fs.access)
const fsUnlink = promisify(fs.unlink)
const fsRmdir = promisify(fs.rmdir)
const fsStat = promisify(fs.stat)
const fsMove = promisify(fs.rename)
const fsReadFile = promisify(fs.readFile)
const fsWriteFile = promisify(fs.writeFile)
const mkdir = promisify(fs.mkdir)
const staticCheckWorker = require.resolve('./utils') const staticCheckWorker = require.resolve('./utils')
export type SsgRoute = { export type SsgRoute = {
...@@ -140,7 +130,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -140,7 +130,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (ciEnvironment.isCI) { if (ciEnvironment.isCI) {
const cacheDir = path.join(distDir, 'cache') const cacheDir = path.join(distDir, 'cache')
const hasCache = await fsAccess(cacheDir) const hasCache = await promises
.access(cacheDir)
.then(() => true) .then(() => true)
.catch(() => false) .catch(() => false)
...@@ -182,7 +173,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -182,7 +173,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
await verifyTypeScriptSetup(dir, pagesDir) await verifyTypeScriptSetup(dir, pagesDir)
try { try {
await fsStat(publicDir) await promises.stat(publicDir)
hasPublicDir = true hasPublicDir = true
} catch (_) {} } catch (_) {}
...@@ -237,7 +228,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -237,7 +228,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (hasPublicDir) { if (hasPublicDir) {
try { try {
await fsStat(path.join(publicDir, '_next')) await promises.stat(path.join(publicDir, '_next'))
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT) throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} catch (err) {} } catch (err) {}
} }
...@@ -310,10 +301,14 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -310,10 +301,14 @@ export default async function build(dir: string, conf = null): Promise<void> {
}), }),
} }
await mkdir(distDir, { recursive: true }) await promises.mkdir(distDir, { recursive: true })
// We need to write the manifest with rewrites before build // We need to write the manifest with rewrites before build
// so serverless can import the manifest // so serverless can import the manifest
await fsWriteFile(routesManifestPath, JSON.stringify(routesManifest), 'utf8') await promises.writeFile(
routesManifestPath,
JSON.stringify(routesManifest),
'utf8'
)
const configs = await Promise.all([ const configs = await Promise.all([
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
...@@ -451,8 +446,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -451,8 +446,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
const serverPropsPages = new Set<string>() const serverPropsPages = new Set<string>()
const additionalSsgPaths = new Map<string, Array<string>>() const additionalSsgPaths = new Map<string, Array<string>>()
const pageInfos = new Map<string, PageInfo>() const pageInfos = new Map<string, PageInfo>()
const pagesManifest = JSON.parse(await fsReadFile(manifestPath, 'utf8')) const pagesManifest = JSON.parse(
const buildManifest = JSON.parse(await fsReadFile(buildManifestPath, 'utf8')) await promises.readFile(manifestPath, 'utf8')
)
const buildManifest = JSON.parse(
await promises.readFile(buildManifestPath, 'utf8')
)
let customAppGetInitialProps: boolean | undefined let customAppGetInitialProps: boolean | undefined
...@@ -563,10 +562,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -563,10 +562,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
'pages', 'pages',
actualPage + '.js' actualPage + '.js'
) )
await fsUnlink(clientBundle) await promises.unlink(clientBundle)
if (config.experimental.modern) { if (config.experimental.modern) {
await fsUnlink(clientBundle.replace(/\.js$/, '.module.js')) await promises.unlink(
clientBundle.replace(/\.js$/, '.module.js')
)
} }
} catch (err) { } catch (err) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
...@@ -672,7 +673,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -672,7 +673,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
} }
}) })
await fsWriteFile( await promises.writeFile(
routesManifestPath, routesManifestPath,
JSON.stringify(routesManifest), JSON.stringify(routesManifest),
'utf8' 'utf8'
...@@ -776,7 +777,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -776,7 +777,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
// remove server bundles that were exported // remove server bundles that were exported
for (const page of staticPages) { for (const page of staticPages) {
const { serverBundle } = pageInfos.get(page)! const { serverBundle } = pageInfos.get(page)!
await fsUnlink(serverBundle) await promises.unlink(serverBundle)
} }
const moveExportedPage = async ( const moveExportedPage = async (
...@@ -803,8 +804,8 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -803,8 +804,8 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (page === '/') pagesManifest['/index'] = relativeDest if (page === '/') pagesManifest['/index'] = relativeDest
if (page === '/.amp') pagesManifest['/index.amp'] = relativeDest if (page === '/.amp') pagesManifest['/index.amp'] = relativeDest
} }
await mkdir(path.dirname(dest), { recursive: true }) await promises.mkdir(path.dirname(dest), { recursive: true })
await fsMove(orig, dest) await promises.rename(orig, dest)
} }
// Only move /404 to /404 when there is no custom 404 as in that case we don't know about the 404 page // Only move /404 to /404 when there is no custom 404 as in that case we don't know about the 404 page
...@@ -866,8 +867,12 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -866,8 +867,12 @@ export default async function build(dir: string, conf = null): Promise<void> {
// remove temporary export folder // remove temporary export folder
await recursiveDelete(exportOptions.outdir) await recursiveDelete(exportOptions.outdir)
await fsRmdir(exportOptions.outdir) await promises.rmdir(exportOptions.outdir)
await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8') await promises.writeFile(
manifestPath,
JSON.stringify(pagesManifest),
'utf8'
)
} }
if (postBuildSpinner) postBuildSpinner.stopAndPersist() if (postBuildSpinner) postBuildSpinner.stopAndPersist()
...@@ -915,7 +920,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -915,7 +920,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
preview: previewProps, preview: previewProps,
} }
await fsWriteFile( await promises.writeFile(
path.join(distDir, PRERENDER_MANIFEST), path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify(prerenderManifest), JSON.stringify(prerenderManifest),
'utf8' 'utf8'
...@@ -932,7 +937,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -932,7 +937,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
dynamicRoutes: {}, dynamicRoutes: {},
preview: previewProps, preview: previewProps,
} }
await fsWriteFile( await promises.writeFile(
path.join(distDir, PRERENDER_MANIFEST), path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify(prerenderManifest), JSON.stringify(prerenderManifest),
'utf8' 'utf8'
...@@ -941,7 +946,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -941,7 +946,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
// await generateClientSsgManifest(prerenderManifest, { distDir, buildId }) // await generateClientSsgManifest(prerenderManifest, { distDir, buildId })
} }
await fsWriteFile( await promises.writeFile(
path.join(distDir, EXPORT_MARKER), path.join(distDir, EXPORT_MARKER),
JSON.stringify({ JSON.stringify({
version: 1, version: 1,
...@@ -950,7 +955,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -950,7 +955,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
}), }),
'utf8' 'utf8'
) )
await fsUnlink(path.join(distDir, EXPORT_DETAIL)).catch(err => { await promises.unlink(path.join(distDir, EXPORT_DETAIL)).catch(err => {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
return Promise.resolve() return Promise.resolve()
} }
...@@ -1065,7 +1070,7 @@ function generateClientSsgManifest( ...@@ -1065,7 +1070,7 @@ function generateClientSsgManifest(
ssgPages ssgPages
)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()` )};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
clientSsgManifestPaths.forEach(clientSsgManifestPath => clientSsgManifestPaths.forEach(clientSsgManifestPath =>
fs.writeFileSync( writeFileSync(
path.join(distDir, clientSsgManifestPath), path.join(distDir, clientSsgManifestPath),
clientSsgManifestContent clientSsgManifestContent
) )
......
import fs from 'fs' import fs from 'fs'
import { promisify } from 'util'
const access = promisify(fs.access)
export async function isWriteable(directory: string): Promise<boolean> { export async function isWriteable(directory: string): Promise<boolean> {
try { try {
await access(directory, (fs.constants || fs).W_OK) await fs.promises.access(directory, (fs.constants || fs).W_OK)
return true return true
} catch (err) { } catch (err) {
return false return false
......
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import fs from 'fs' import { promises } from 'fs'
import path from 'path' import path from 'path'
import { promisify } from 'util'
import resolve from 'next/dist/compiled/resolve/index.js' import resolve from 'next/dist/compiled/resolve/index.js'
import { execOnce } from '../../next-server/lib/utils' import { execOnce } from '../../next-server/lib/utils'
const readdir = promisify(fs.readdir)
export type PluginMetaData = { export type PluginMetaData = {
requiredEnv: string[] requiredEnv: string[]
middleware: string[] middleware: string[]
...@@ -65,7 +62,7 @@ async function collectPluginMeta( ...@@ -65,7 +62,7 @@ async function collectPluginMeta(
// TODO: add err.sh explaining requirements // TODO: add err.sh explaining requirements
let middleware: string[] = [] let middleware: string[] = []
try { try {
middleware = await readdir(path.join(pkgDir, 'src')) middleware = await promises.readdir(path.join(pkgDir, 'src'))
} catch (err) { } catch (err) {
if (err.code !== 'ENOENT') { if (err.code !== 'ENOENT') {
console.error(err) console.error(err)
......
import { join } from 'path' import { join } from 'path'
import { promisify } from 'util' import { promises } from 'fs'
import fs from 'fs'
import { IS_BUNDLED_PAGE_REGEX } from '../../../next-server/lib/constants' import { IS_BUNDLED_PAGE_REGEX } from '../../../next-server/lib/constants'
import { Compiler } from 'webpack' import { Compiler } from 'webpack'
const unlink = promisify(fs.unlink)
// Makes sure removed pages are removed from `.next` in development // Makes sure removed pages are removed from `.next` in development
export class UnlinkRemovedPagesPlugin { export class UnlinkRemovedPagesPlugin {
prevAssets: any prevAssets: any
...@@ -27,7 +24,7 @@ export class UnlinkRemovedPagesPlugin { ...@@ -27,7 +24,7 @@ export class UnlinkRemovedPagesPlugin {
removed.map(async f => { removed.map(async f => {
const path = join((compiler as any).outputPath, f) const path = join((compiler as any).outputPath, f)
try { try {
await unlink(path) await promises.unlink(path)
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') return if (err.code === 'ENOENT') return
throw err throw err
......
import fs from 'fs' import { promises } from 'fs'
import { promisify } from 'util'
import { join } from 'path' import { join } from 'path'
import { BUILD_ID_FILE } from '../next-server/lib/constants' import { BUILD_ID_FILE } from '../next-server/lib/constants'
const writeFile = promisify(fs.writeFile)
export async function writeBuildId( export async function writeBuildId(
distDir: string, distDir: string,
buildId: string buildId: string
): Promise<void> { ): Promise<void> {
const buildIdPath = join(distDir, BUILD_ID_FILE) const buildIdPath = join(distDir, BUILD_ID_FILE)
await writeFile(buildIdPath, buildId, 'utf8') await promises.writeFile(buildIdPath, buildId, 'utf8')
} }
import chalk from 'next/dist/compiled/chalk' import chalk from 'next/dist/compiled/chalk'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { import {
copyFile as copyFileOrig, promises,
existsSync, existsSync,
exists as existsOrig, exists as existsOrig,
mkdir as mkdirOrig,
readFileSync, readFileSync,
writeFileSync, writeFileSync,
} from 'fs' } from 'fs'
...@@ -37,8 +36,6 @@ import { Telemetry } from '../telemetry/storage' ...@@ -37,8 +36,6 @@ import { Telemetry } from '../telemetry/storage'
import { normalizePagePath } from '../next-server/server/normalize-page-path' import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { loadEnvConfig } from '../lib/load-env-config' import { loadEnvConfig } from '../lib/load-env-config'
const copyFile = promisify(copyFileOrig)
const mkdir = promisify(mkdirOrig)
const exists = promisify(existsOrig) const exists = promisify(existsOrig)
const createProgress = (total: number, label = 'Exporting') => { const createProgress = (total: number, label = 'Exporting') => {
...@@ -189,7 +186,7 @@ export default async function( ...@@ -189,7 +186,7 @@ export default async function(
} }
await recursiveDelete(join(outDir)) await recursiveDelete(join(outDir))
await mkdir(join(outDir, '_next', buildId), { recursive: true }) await promises.mkdir(join(outDir, '_next', buildId), { recursive: true })
writeFileSync( writeFileSync(
join(distDir, EXPORT_DETAIL), join(distDir, EXPORT_DETAIL),
...@@ -393,14 +390,14 @@ export default async function( ...@@ -393,14 +390,14 @@ export default async function(
) )
const jsonDest = join(pagesDataDir, `${route}.json`) const jsonDest = join(pagesDataDir, `${route}.json`)
await mkdir(dirname(htmlDest), { recursive: true }) await promises.mkdir(dirname(htmlDest), { recursive: true })
await mkdir(dirname(jsonDest), { recursive: true }) await promises.mkdir(dirname(jsonDest), { recursive: true })
await copyFile(`${orig}.html`, htmlDest) await promises.copyFile(`${orig}.html`, htmlDest)
await copyFile(`${orig}.json`, jsonDest) await promises.copyFile(`${orig}.json`, jsonDest)
if (await exists(`${orig}.amp.html`)) { if (await exists(`${orig}.amp.html`)) {
await mkdir(dirname(ampHtmlDest), { recursive: true }) await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
await copyFile(`${orig}.amp.html`, ampHtmlDest) await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
} }
}) })
) )
......
import { promisify } from 'util'
import url from 'url' import url from 'url'
import { extname, join, dirname, sep } from 'path' import { extname, join, dirname, sep } from 'path'
import { renderToHTML } from '../next-server/server/render' import { renderToHTML } from '../next-server/server/render'
import { access, mkdir as mkdirOrig, writeFile } from 'fs' import { promises } from 'fs'
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator' import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import { loadComponents } from '../next-server/server/load-components' import { loadComponents } from '../next-server/server/load-components'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
...@@ -20,9 +19,6 @@ if (!global.fetch) { ...@@ -20,9 +19,6 @@ if (!global.fetch) {
} }
const envConfig = require('../next-server/lib/runtime-config') const envConfig = require('../next-server/lib/runtime-config')
const writeFileP = promisify(writeFile)
const accessP = promisify(access)
const mkdir = promisify(mkdirOrig)
global.__NEXT_DATA__ = { global.__NEXT_DATA__ = {
nextExport: true, nextExport: true,
...@@ -121,7 +117,7 @@ export default async function({ ...@@ -121,7 +117,7 @@ export default async function({
const baseDir = join(outDir, dirname(htmlFilename)) const baseDir = join(outDir, dirname(htmlFilename))
let htmlFilepath = join(outDir, htmlFilename) let htmlFilepath = join(outDir, htmlFilename)
await mkdir(baseDir, { recursive: true }) await promises.mkdir(baseDir, { recursive: true })
let html let html
let curRenderOpts = {} let curRenderOpts = {}
let renderMethod = renderToHTML let renderMethod = renderToHTML
...@@ -243,7 +239,7 @@ export default async function({ ...@@ -243,7 +239,7 @@ export default async function({
const ampHtmlFilepath = join(outDir, ampHtmlFilename) const ampHtmlFilepath = join(outDir, ampHtmlFilename)
try { try {
await accessP(ampHtmlFilepath) await promises.access(ampHtmlFilepath)
} catch (_) { } catch (_) {
// make sure it doesn't exist from manual mapping // make sure it doesn't exist from manual mapping
let ampHtml let ampHtml
...@@ -263,8 +259,8 @@ export default async function({ ...@@ -263,8 +259,8 @@ export default async function({
if (!curRenderOpts.ampSkipValidation) { if (!curRenderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1') await validateAmp(ampHtml, page + '?amp=1')
} }
await mkdir(ampBaseDir, { recursive: true }) await promises.mkdir(ampBaseDir, { recursive: true })
await writeFileP(ampHtmlFilepath, ampHtml, 'utf8') await promises.writeFile(ampHtmlFilepath, ampHtml, 'utf8')
} }
} }
...@@ -274,12 +270,16 @@ export default async function({ ...@@ -274,12 +270,16 @@ export default async function({
htmlFilename.replace(/\.html$/, '.json') htmlFilename.replace(/\.html$/, '.json')
) )
await mkdir(dirname(dataFile), { recursive: true }) await promises.mkdir(dirname(dataFile), { recursive: true })
await writeFileP(dataFile, JSON.stringify(curRenderOpts.pageData), 'utf8') await promises.writeFile(
dataFile,
JSON.stringify(curRenderOpts.pageData),
'utf8'
)
} }
results.fromBuildExportRevalidate = curRenderOpts.revalidate results.fromBuildExportRevalidate = curRenderOpts.revalidate
await writeFileP(htmlFilepath, html, 'utf8') await promises.writeFile(htmlFilepath, html, 'utf8')
return results return results
} catch (error) { } catch (error) {
console.error( console.error(
......
import fs from 'fs' import { promises, constants } from 'fs'
import { promisify } from 'util'
const access = promisify(fs.access)
export async function fileExists(fileName: string): Promise<boolean> { export async function fileExists(fileName: string): Promise<boolean> {
try { try {
await access(fileName, fs.constants.F_OK) await promises.access(fileName, constants.F_OK)
return true return true
} catch (err) { } catch (err) {
if (err.code === 'ENOENT') { if (err.code === 'ENOENT') {
......
import path from 'path' import path from 'path'
import fs from 'fs' import { promises, constants } from 'fs'
import { promisify } from 'util'
import { Sema } from 'next/dist/compiled/async-sema' import { Sema } from 'next/dist/compiled/async-sema'
const mkdir = promisify(fs.mkdir) const COPYFILE_EXCL = constants.COPYFILE_EXCL
const stat = promisify(fs.stat)
const readdir = promisify(fs.readdir)
const copyFile = promisify(fs.copyFile)
const COPYFILE_EXCL = fs.constants.COPYFILE_EXCL
export async function recursiveCopy( export async function recursiveCopy(
source: string, source: string,
...@@ -31,13 +25,13 @@ export async function recursiveCopy( ...@@ -31,13 +25,13 @@ export async function recursiveCopy(
async function _copy(item: string) { async function _copy(item: string) {
const target = item.replace(from, to) const target = item.replace(from, to)
const stats = await stat(item) const stats = await promises.stat(item)
await sema.acquire() await sema.acquire()
if (stats.isDirectory()) { if (stats.isDirectory()) {
try { try {
await mkdir(target) await promises.mkdir(target)
} catch (err) { } catch (err) {
// do not throw `folder already exists` errors // do not throw `folder already exists` errors
if (err.code !== 'EEXIST') { if (err.code !== 'EEXIST') {
...@@ -45,7 +39,7 @@ export async function recursiveCopy( ...@@ -45,7 +39,7 @@ export async function recursiveCopy(
} }
} }
sema.release() sema.release()
const files = await readdir(item) const files = await promises.readdir(item)
await Promise.all(files.map(file => _copy(path.join(item, file)))) await Promise.all(files.map(file => _copy(path.join(item, file))))
} else if ( } else if (
stats.isFile() && stats.isFile() &&
...@@ -53,7 +47,11 @@ export async function recursiveCopy( ...@@ -53,7 +47,11 @@ export async function recursiveCopy(
// we remove the base path (from) and replace \ by / (windows) // we remove the base path (from) and replace \ by / (windows)
filter(item.replace(from, '').replace(/\\/g, '/')) filter(item.replace(from, '').replace(/\\/g, '/'))
) { ) {
await copyFile(item, target, overwrite ? undefined : COPYFILE_EXCL) await promises.copyFile(
item,
target,
overwrite ? undefined : COPYFILE_EXCL
)
sema.release() sema.release()
} }
} }
......
import fs from 'fs' import { promises } from 'fs'
import { join } from 'path' import { join } from 'path'
import { promisify } from 'util' import { promisify } from 'util'
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
const rmdir = promisify(fs.rmdir)
const unlink = promisify(fs.unlink)
const sleep = promisify(setTimeout) const sleep = promisify(setTimeout)
const unlinkFile = async (p: string, t = 1): Promise<void> => { const unlinkFile = async (p: string, t = 1): Promise<void> => {
try { try {
await unlink(p) await promises.unlink(p)
} catch (e) { } catch (e) {
if ( if (
(e.code === 'EBUSY' || (e.code === 'EBUSY' ||
...@@ -45,7 +41,7 @@ export async function recursiveDelete( ...@@ -45,7 +41,7 @@ export async function recursiveDelete(
): Promise<void> { ): Promise<void> {
let result let result
try { try {
result = await readdir(dir) result = await promises.readdir(dir)
} catch (e) { } catch (e) {
if (e.code === 'ENOENT') { if (e.code === 'ENOENT') {
return return
...@@ -56,7 +52,7 @@ export async function recursiveDelete( ...@@ -56,7 +52,7 @@ export async function recursiveDelete(
await Promise.all( await Promise.all(
result.map(async (part: string) => { result.map(async (part: string) => {
const absolutePath = join(dir, part) const absolutePath = join(dir, part)
const pathStat = await stat(absolutePath).catch(e => { const pathStat = await promises.stat(absolutePath).catch(e => {
if (e.code !== 'ENOENT') throw e if (e.code !== 'ENOENT') throw e
}) })
if (!pathStat) { if (!pathStat) {
...@@ -66,7 +62,7 @@ export async function recursiveDelete( ...@@ -66,7 +62,7 @@ export async function recursiveDelete(
const pp = join(previousPath, part) const pp = join(previousPath, part)
if (pathStat.isDirectory() && (!exclude || !exclude.test(pp))) { if (pathStat.isDirectory() && (!exclude || !exclude.test(pp))) {
await recursiveDelete(absolutePath, exclude, pp) await recursiveDelete(absolutePath, exclude, pp)
return rmdir(absolutePath) return promises.rmdir(absolutePath)
} }
if (!exclude || !exclude.test(pp)) { if (!exclude || !exclude.test(pp)) {
......
import fs from 'fs' import { promises } from 'fs'
import { join } from 'path' import { join } from 'path'
import { promisify } from 'util'
const readdir = promisify(fs.readdir)
const stat = promisify(fs.stat)
/** /**
* Recursively read directory * Recursively read directory
...@@ -20,14 +16,14 @@ export async function recursiveReadDir( ...@@ -20,14 +16,14 @@ export async function recursiveReadDir(
arr: string[] = [], arr: string[] = [],
rootDir: string = dir rootDir: string = dir
): Promise<string[]> { ): Promise<string[]> {
const result = await readdir(dir) const result = await promises.readdir(dir)
await Promise.all( await Promise.all(
result.map(async (part: string) => { result.map(async (part: string) => {
const absolutePath = join(dir, part) const absolutePath = join(dir, part)
if (ignore && ignore.test(part)) return if (ignore && ignore.test(part)) return
const pathStat = await stat(absolutePath) const pathStat = await promises.stat(absolutePath)
if (pathStat.isDirectory()) { if (pathStat.isDirectory()) {
await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir) await recursiveReadDir(absolutePath, filter, ignore, arr, rootDir)
......
...@@ -2,17 +2,13 @@ import chalk from 'next/dist/compiled/chalk' ...@@ -2,17 +2,13 @@ import chalk from 'next/dist/compiled/chalk'
import fs from 'fs' import fs from 'fs'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import { promisify } from 'util'
import { fileExists } from './file-exists' import { fileExists } from './file-exists'
import { recursiveReadDir } from './recursive-readdir' import { recursiveReadDir } from './recursive-readdir'
import { resolveRequest } from './resolve-request' import { resolveRequest } from './resolve-request'
const writeFile = promisify(fs.writeFile)
const readFile = promisify(fs.readFile)
function writeJson(fileName: string, object: object): Promise<void> { function writeJson(fileName: string, object: object): Promise<void> {
return writeFile( return fs.promises.writeFile(
fileName, fileName,
JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL
) )
...@@ -109,9 +105,9 @@ export async function verifyTypeScriptSetup( ...@@ -109,9 +105,9 @@ export async function verifyTypeScriptSetup(
let firstTimeSetup = false let firstTimeSetup = false
if (hasTsConfig) { if (hasTsConfig) {
const tsConfig = await readFile(tsConfigPath, 'utf8').then(val => const tsConfig = await fs.promises
val.trim() .readFile(tsConfigPath, 'utf8')
) .then(val => val.trim())
firstTimeSetup = tsConfig === '' || tsConfig === '{}' firstTimeSetup = tsConfig === '' || tsConfig === '{}'
} else { } else {
const hasTypeScriptFiles = await hasTypeScript(pagesDir) const hasTypeScriptFiles = await hasTypeScript(pagesDir)
......
import fs from 'fs' import { promises } from 'fs'
import { join } from 'path' import { join } from 'path'
import { promisify } from 'util'
import { import {
PAGES_MANIFEST, PAGES_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
...@@ -8,8 +7,6 @@ import { ...@@ -8,8 +7,6 @@ import {
} from '../lib/constants' } from '../lib/constants'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
const readFile = promisify(fs.readFile)
export function pageNotFoundError(page: string): Error { export function pageNotFoundError(page: string): Error {
const err: any = new Error(`Cannot find module for page: ${page}`) const err: any = new Error(`Cannot find module for page: ${page}`)
err.code = 'ENOENT' err.code = 'ENOENT'
...@@ -54,7 +51,7 @@ export function requirePage( ...@@ -54,7 +51,7 @@ export function requirePage(
): any { ): any {
const pagePath = getPagePath(page, distDir, serverless) const pagePath = getPagePath(page, distDir, serverless)
if (pagePath.endsWith('.html')) { if (pagePath.endsWith('.html')) {
return readFile(pagePath, 'utf8') return promises.readFile(pagePath, 'utf8')
} }
return require(pagePath) return require(pagePath)
} }
import fs from 'fs' import { promises, readFileSync } from 'fs'
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import path from 'path' import path from 'path'
import { promisify } from 'util'
import { PrerenderManifest } from '../../build' import { PrerenderManifest } from '../../build'
import { PRERENDER_MANIFEST } from '../lib/constants' import { PRERENDER_MANIFEST } from '../lib/constants'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
const mkdir = promisify(fs.mkdir)
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
function toRoute(pathname: string): string { function toRoute(pathname: string): string {
return pathname.replace(/\/$/, '').replace(/\/index$/, '') || '/' return pathname.replace(/\/$/, '').replace(/\/index$/, '') || '/'
} }
...@@ -86,7 +81,7 @@ export function initializeSprCache({ ...@@ -86,7 +81,7 @@ export function initializeSprCache({
} }
} else { } else {
prerenderManifest = JSON.parse( prerenderManifest = JSON.parse(
fs.readFileSync(path.join(distDir, PRERENDER_MANIFEST), 'utf8') readFileSync(path.join(distDir, PRERENDER_MANIFEST), 'utf8')
) )
} }
...@@ -102,7 +97,7 @@ export function initializeSprCache({ ...@@ -102,7 +97,7 @@ export function initializeSprCache({
export async function getFallback(page: string): Promise<string> { export async function getFallback(page: string): Promise<string> {
page = normalizePagePath(page) page = normalizePagePath(page)
return readFile(getSeedPath(page, 'html'), 'utf8') return promises.readFile(getSeedPath(page, 'html'), 'utf8')
} }
// get data from SPR cache if available // get data from SPR cache if available
...@@ -117,9 +112,12 @@ export async function getSprCache( ...@@ -117,9 +112,12 @@ export async function getSprCache(
// let's check the disk for seed data // let's check the disk for seed data
if (!data) { if (!data) {
try { try {
const html = await readFile(getSeedPath(pathname, 'html'), 'utf8') const html = await promises.readFile(
getSeedPath(pathname, 'html'),
'utf8'
)
const pageData = JSON.parse( const pageData = JSON.parse(
await readFile(getSeedPath(pathname, 'json'), 'utf8') await promises.readFile(getSeedPath(pathname, 'json'), 'utf8')
) )
data = { data = {
...@@ -182,9 +180,9 @@ export async function setSprCache( ...@@ -182,9 +180,9 @@ export async function setSprCache(
if (sprOptions.flushToDisk) { if (sprOptions.flushToDisk) {
try { try {
const seedPath = getSeedPath(pathname, 'html') const seedPath = getSeedPath(pathname, 'html')
await mkdir(path.dirname(seedPath), { recursive: true }) await promises.mkdir(path.dirname(seedPath), { recursive: true })
await writeFile(seedPath, data.html, 'utf8') await promises.writeFile(seedPath, data.html, 'utf8')
await writeFile( await promises.writeFile(
getSeedPath(pathname, 'json'), getSeedPath(pathname, 'json'),
JSON.stringify(data.pageData), JSON.stringify(data.pageData),
'utf8' 'utf8'
......
...@@ -7,7 +7,6 @@ import Worker from 'jest-worker' ...@@ -7,7 +7,6 @@ import Worker from 'jest-worker'
import { join, relative, resolve, sep } from 'path' import { join, relative, resolve, sep } from 'path'
import React from 'react' import React from 'react'
import { UrlWithParsedQuery } from 'url' import { UrlWithParsedQuery } from 'url'
import { promisify } from 'util'
import Watchpack from 'watchpack' import Watchpack from 'watchpack'
import { ampValidation } from '../build/output/index' import { ampValidation } from '../build/output/index'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
...@@ -39,8 +38,6 @@ if (typeof React.Suspense === 'undefined') { ...@@ -39,8 +38,6 @@ if (typeof React.Suspense === 'undefined') {
) )
} }
const fsStat = promisify(fs.stat)
export default class DevServer extends Server { export default class DevServer extends Server {
private devReady: Promise<void> private devReady: Promise<void>
private setDevReady?: Function private setDevReady?: Function
...@@ -320,7 +317,7 @@ export default class DevServer extends Server { ...@@ -320,7 +317,7 @@ export default class DevServer extends Server {
if (pathname!.startsWith('/_next')) { if (pathname!.startsWith('/_next')) {
try { try {
await fsStat(join(this.publicDir, '_next')) await fs.promises.stat(join(this.publicDir, '_next'))
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT) throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} catch (err) {} } catch (err) {}
} }
...@@ -563,7 +560,7 @@ export default class DevServer extends Server { ...@@ -563,7 +560,7 @@ export default class DevServer extends Server {
async hasPublicFile(path: string) { async hasPublicFile(path: string) {
try { try {
const info = await fsStat(join(this.publicDir, path)) const info = await fs.promises.stat(join(this.publicDir, path))
return info.isFile() return info.isFile()
} catch (_) { } catch (_) {
return false return false
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment