如何在 Netlify 上的 Next.js 中获取目录列表

deb*_*ute 5 javascript node.js 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)"
]
}
Run Code Online (Sandbox Code Playgroud)

这是我的next.config.js

module.exports = {
    serverRuntimeConfig: {
        PROJECT_ROOT: __dirname
    },
    target: 'experimental-serverless-trace'
};
Run Code Online (Sandbox Code Playgroud)

这是我的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...
    });

    ...
}
Run Code Online (Sandbox Code Playgroud)

这是config/app.js

import getConfig from 'next/config';

const { serverRuntimeConfig } = getConfig();

export const project_root = serverRuntimeConfig.PROJECT_ROOT;
Run Code Online (Sandbox Code Playgroud)

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

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

小智 0

我遇到了同样的问题,我通过验证目录是否存在来修复,如果不存在,则创建一个目录:

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

    if (fs?.existsSync(videosPath)) { // Validate if directory exist
        return fs.readdirSync(videosPath).forEach(video => {
            // Do stuff with a path...
        });
    } else { // If not exist create a directory
        return fs?.mkdirSync(videosPath, { recursive: true });
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)