代码之家  ›  专栏  ›  技术社区  ›  james emanon

writeFileSync未创建和写入文件

  •  0
  • james emanon  · 技术社区  · 4 年前

    因此,我在Next.js中有一堆SSG页面,因此,我正在创建导航,其中有一堆路线。所以,我想“缓存”第一个api调用,然后只获取缓存的(写入文件数据)。我正在使用这个,它并没有创建文件。我得到了以下错误,因此,我总是点击api。

    我登录捕获,它会给出错误。从不创建文件。

    错误:

    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
    }
    
    0 回复  |  直到 4 年前
        1
  •  3
  •   traynor    4 年前

    它失败了,因为中的文件路径 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
    
    }
    
    推荐文章