它失败了,因为中的文件路径
ROUTE_CACHE_PATH
和
readFileSync
自始至终都是不正确的。
请尝试设置正确的路径,然后全程使用:
// setup the correct path to file, use it throughout
// writes to the file `routes` in CWD
const ROUTE_CACHE_PATH = path.resolve(path.join(process.cwd(), 'routes'));
现在请通篇参考:
fs.readFileSync(ROUTE_CACHE_PATH, 'utf8')
和
fs.writeFileSync(
ROUTE_CACHE_PATH,
请记住
JSON.parse
如果它不是您发送的可解析数据,那么这里也可能失败,所以您可能也会考虑添加一个处理程序,或者可能是在发送方。
有了这个代码,阅读和写作就有点独立了。因此,更好的方法可能是将文件写入错误部分IMHO:
try {
readFile
} catch() {
writeFile
}
这是重新排列的代码:
import fs from 'fs';
import path from 'path';
/* api */
import routes from '@api/rest/routes';
// setup the correct path to file, use it throughout
// writes to the file `routes` in CWD
const ROUTE_CACHE_PATH = path.resolve(path.join(process.cwd(), 'routes'));
export default async function getCacheRoutes() {
// setup variables to be accessible for later
let cachedData;
let data;
// first, read the file
// if it fails, there is no file
// so move the file writing to the error part
// note that parsing might also fail, so handle that there too
try {
// parsing might fail here though..
cachedData = JSON.parse(
fs.readFileSync(ROUTE_CACHE_PATH, 'utf8')
)
} catch (error) {
// reading failed, handle file writing
// parsing and other errors here
console.log(error);
// if there is no file, get data and write a fresh file
if (error.code === 'ENOENT') {
// todo: make sure it's always a JSON as string,
// otherwise parsing will fail..
data = await routes();
try {
fs.writeFileSync(
ROUTE_CACHE_PATH,
JSON.stringify(data), {
flag: 'w'
}
)
} catch (error) {
// parsing might fail..
console.log(error);
}
} else {
// or some other error: JSON parsing failed, for example
console.log('handle some other error', error);
}
cachedData = data;
}
return cachedData
}