首页 > 解决方案 > 如何在 Netlify 上的 Next.js 中获取目录列表

问题描述

我在 Netlify 上的 Next.js 中获取目录列表时遇到问题。它在localhost上运行良好,但是当我将站点部署到 Netlify 时,出现此错误:

{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "Error: ENOENT: no such file or directory, scandir '/opt/build/repo/storage/videos/'",
"trace": [
"Runtime.UnhandledPromiseRejection: Error: ENOENT: no such file or directory, scandir '/opt/build/repo/storage/videos/'",
"    at process.<anonymous> (/var/runtime/index.js:35:15)",
"    at process.emit (events.js:314:20)",
"    at processPromiseRejections (internal/process/promises.js:209:33)",
"    at processTicksAndRejections (internal/process/task_queues.js:98:32)"
]
}

这是我的next.config.js

module.exports = {
    serverRuntimeConfig: {
        PROJECT_ROOT: __dirname
    },
    target: 'experimental-serverless-trace'
};

这是我的pages/index.js

import fs from 'fs';
import path from 'path';
import { project_root } from '@config/app';

...

export async function getServerSideProps() {
    const videosPath = path.join(project_root, './storage/videos/');

    fs.readdirSync(videosPath).forEach(video => {
        // Do stuff with a path...
    });

    ...
}

这是config/app.js

import getConfig from 'next/config';

const { serverRuntimeConfig } = getConfig();

export const project_root = serverRuntimeConfig.PROJECT_ROOT;

我是 Next.js 和 Netlify 的新手,所以我不确定是什么问题。我看到/opt/build/repo/storage/videos/正在readdirSync读取的路径无效,可能应该是这样var/runtime/storage/videos/的,但我不知道如何修复它并使其在 Netlify 和 localhost 上都能正常工作。

PS:是的,我在storage/videos文件夹和 git 上都有文件,在 Netlify 上我为项目安装了这些插件: 在此处输入图像描述

标签: javascriptnode.jsnext.jsnetlify

解决方案


推荐阅读