【问题标题】:writeFileSync NOT creating and writing to filewriteFileSync 不创建和写入文件
【发布时间】: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
}

【问题讨论】:

    标签: node.js next.js


    【解决方案1】:

    失败是因为ROUTE_CACHE_PATHreadFileSync中的文件路径始终不正确。

    尝试设置正确的路径,然后在整个过程中使用它:

    // 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 也可能在此处失败,因此您也可以考虑为此添加处理程序,或者可能在发送方部分。

    使用此代码,读取和写入有点独立。因此,更好的方法可能是将文件写入错误部分,恕我直言:

    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
    
    }
    

    【讨论】:

    • 那行得通....我的路径不好.. arrggg。不敢相信我错过了。谢谢。
    • 我确实还有一个问题,您认为将时间戳应用于 json 是合适的...并阅读它,以便给定“持续时间”的时间,我们将其删除并创建一条新路线缓存,否则它会随着时间的推移变得陈旧?
    • 我很高兴它成功了,是的,路径很棘手,TBH,我总是 console.log 所有路径。嗯,那不应该伤害。我想任何缓存的数据都是一样的,所以这取决于数据更改的频率。你可以考虑每隔一段时间使用 cron/scheduled 任务来运行一些更新文件的脚本,很多选项..
    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2013-03-10
    • 1970-01-01
    • 2011-12-11
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多