You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Node.js根目录index.js向public目录script.js导入变量?

问题描述

我想把根目录Node.js的index.js文件中的变量,导入到public目录下的script.js文件中(知道Node.js的index文件不该放public目录)。

我的index.js代码:

const { readFile, readFileSync } = require("fs");
const express = require("express");

const app = express();
app.use(express.static("public"));

const txt = readFileSync("./public/articles/1/title.txt", "utf-8");


app.get("/", (request, response) => {
    readFile("./public/html/index.html", "utf-8", (err, html) => {response.send(html);});
});


app.listen(process.env.PORT || 3000, () => console.log(`Live at http://localhost:3000`))

module.exports = { txt };

我尝试在./public/js/script.js中导入txt:

import txt from "../index.js";
console.log(txt);

但程序尝试从public/index.js获取文件,导致404错误。请问有没有方法从index.js获取该变量,还是应该将index.js移到public目录中?


解决方案

绝对不要把index.js移到public目录,后端代码暴露给前端会带来严重的安全风险。

核心原因:前端浏览器运行的script.js和后端Node.js运行的index.js是完全独立的两个环境,不能直接通过import导入后端文件——浏览器会把../index.js解析成相对于public目录的路径,去请求不存在的public/index.js,所以出现404。

下面是两种可行的解决方法:

方法一:页面渲染时注入变量

修改后端逻辑,把txt变量注入到HTML中,让前端脚本直接读取:

  1. 更新index.js的根路由处理:
app.get("/", (request, response) => {
    readFile("./public/html/index.html", "utf-8", (err, html) => {
        // 用JSON.stringify处理特殊字符,避免注入问题
        const injectedHtml = html.replace("{{txt}}", JSON.stringify(txt));
        response.send(injectedHtml);
    });
});
  1. 在index.html中引入脚本前定义全局变量:
<!-- 先定义全局变量,再引入script.js -->
<script>
    const txt = {{txt}};
</script>
<script src="/js/script.js"></script>
  1. 修改script.js直接使用全局变量:
console.log(txt);

方法二:通过API接口获取变量

后端新增一个接口返回txt的值,前端通过fetch请求获取:

  1. 在index.js中添加API路由:
// 新增接口返回txt变量
app.get("/api/get-txt", (req, res) => {
    res.json({ txt });
});
  1. 更新script.js请求接口:
fetch("/api/get-txt")
    .then(res => res.json())
    .then(data => {
        console.log(data.txt);
        // 在这里处理txt变量
    })
    .catch(err => console.error("获取数据失败:", err));

内容的提问来源于stack exchange,提问作者KisaKot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 05:07:18