next.js ENOENT:没有此类文件或目录readFileSync [重复]

ohfgkhjo  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(174)

此问题在此处已有答案

Next.js: How to get static assets from within getStaticProps(1个答案)
1年前关闭。
我尝试将json文件路径传递给ebay auth函数以获取令牌。这只需要声明文件名就可以在本地工作。但是,由于我的下一个js应用程序在Vercel中部署为Node,我需要调用readFileSync以确保json文件包含在构建中。
为了做到这一点,我实现了:-

const { readFileSync } = require("fs");
  var path = require("path");

  const file = readFileSync(
    path.join(__dirname, "config/eBayJson.json"),
    "utf8"
  );

在我的getServerSideProps中。
然而,尽管我的文件显然位于正确的路径,并且我正在调用__dirname以确保路径正确,但我仍然收到错误,现在在本地和vercel部署中,该文件或目录不存在:-

Error: ENOENT: no such file or directory, open '\config\eBayJson.json'
    at Object.openSync (node:fs:490:3)
    at readFileSync (node:fs:391:35)
    at getServerSideProps (D:\Web\StoreApp\nextjs-store\.next\server\pages\inventory.js:3846:16)
    at renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\render.js:40:221)        
    at async D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:112:97
    at async D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:105:142
    at async DevServer.renderToHTMLWithComponents (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:137:387)
    at async DevServer.renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:138:522)
    at async DevServer.renderToHTML (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\server\next-dev-server.js:35:578)
    at async DevServer.render (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:75:236)
    at async Object.fn (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:59:580)    at async Router.execute (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\router.js:25:67) 
    at async DevServer.run (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:69:1042)
    at async DevServer.handleRequest (D:\Web\StoreApp\nextjs-store\node_modules\next\dist\next-server\server\next-server.js:34:504) {
  errno: -4058,
  syscall: 'open',
  path: '\\config\\eBayJson.json'
}

我不知道我做错了什么。我能找到的大多数堆栈溢出的答案都是关于缺少__dirname的,我已经包括了。
任何帮助非常感谢!

deyfvvtc

deyfvvtc1#

已解决
感谢@juliomalves和此帖子的帮助:- https://stackoverflow.com/a/65861629/1870780,用更新的代码解决了我的问题:

export async function getServerSideProps(req, res) {
      const { readFileSync } = require("fs");
      var path = require("path");
      const configDirectory = path.resolve(process.cwd(), "config");
      const file = readFileSync(
        path.join(configDirectory, "eBayJson.json"),
        "utf8"
      );
    
      const EbayAuthToken = require("ebay-oauth-nodejs-client");
      const ebayAuthToken = new EbayAuthToken({
        filePath: path.join(configDirectory, "eBayJson.json"),
        // input file path.
      });

相关问题