【发布时间】:2022-01-25 18:38:18
【问题描述】:
所以,我在 Next.js 中有一堆 SSG 页面,因此,我正在创建包含一堆路线的导航。所以,我想“缓存”第一个 api 调用,然后获取缓存(写入文件数据)。我正在使用它,它没有创建文件。我收到以下错误,因此,我总是点击 api。
我登录catch,它给出了错误。永远不会创建文件。
错误:
Error: ENOENT: no such file or directory, open '/Users/jim/company/clientapp/.next/server/pages/Users/jim/company/clientapp/.routes'
我的代码:
import fs from 'fs';
import path from 'path';
/* api */
import routes from '@api/rest/routes';
const ROUTE_CACHE_PATH = path.resolve('.routes');
export default async function getCacheRoutes() {
let cachedData
try {
cachedData = JSON.parse(
fs.readFileSync(path.join(__dirname, ROUTE_CACHE_PATH), 'utf8')
)
} catch (error) {
// logger here
}
if (!cachedData) {
const data = await routes() // this is the api request, it works
try {
fs.writeFileSync(
path.join(__dirname, ROUTE_CACHE_PATH),
JSON.stringify(data),
{ flag: 'w' }. // With or without this, doesn't work.
)
} catch (error) {
// Logger here
}
cachedData = data
}
return cachedData
}
【问题讨论】: