__dirname 未在 nodejs 中定义

时间:2021-01-31 20:00:54

标签: javascript node.js server

所以我有一个我正在制作的应用程序,它有一个 React 前端和 Node-express 后端。出于某种原因,当我以任何方式访问变量 __dirname 时,它说它是未定义的,即使智能感知可以检测到它。

index.js

import express from "express";
import http from "http";
import chalk from "chalk";
import path from "path";

const PORT = process.env.PORT,
app = express(),
server = http.createServer(app),
log = console.log;

console.log(__dirname);

app.use(express.static(path.join(__dirname, "client", "build")));
app.set("views", path.join(__dirname, "client", "build"));

app.get("/", function (req, res) {
    res.render(path.join(__dirname, "client", "build", "index.js"));
});

server.listen(PORT, function () {
    log(chalk.green("Listening on PORT:"), PORT);
});

终端输出

<块引用>

(node:29852) ExperimentalWarning:ESM 模块加载器是实验性的。 file:///home/david/Downloads/coding/PWA/React/startup/meter-detection-startup/index.js:11 console.log(__dirname); ^

<块引用>

ReferenceError: __dirname 未定义 在 file:///home/david/Downloads/coding/PWA/React/startup/meter-detection-startup/index.js:11:13 在 ModuleJob.run (internal/modules/esm/module_job.js:139:37) 在异步 Loader.import (internal/modules/esm/loader.js:179:24)

0 个答案:

没有答案