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

Flask应用中main.js无法从.txt文件读取数组的求助

问题根源

fs是Node.js专属的服务器端模块,只能在Node环境下运行。你的main.js是在浏览器端执行的前端脚本,浏览器不支持require('fs')这类Node API,这就是为什么单独用node start.js能成功,但放到前端main.js里就失效。而myFunctionTest能正常工作,是因为它完全是前端可执行的纯JS逻辑,没有依赖服务器端模块。

解决方案

下面提供两种可行的解决思路,根据你的场景选择:

方案1:后端接口返回数据(推荐,更安全可控)

在Flask后端写一个接口,用Python读取txt文件并转成数组,再通过接口返回给前端,前端通过HTTP请求获取数据。

步骤1:Flask后端添加接口(app.py)

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/get-data')
def get_data():
    # 读取txt文件,根据你的文件格式调整解析逻辑
    # 假设txt每行是一个数组元素,过滤空行
    with open('File.txt', 'r', encoding='utf-8') as f:
        data_array = [line.strip() for line in f if line.strip()]
    return jsonify(data_array)

if __name__ == '__main__':
    app.run(debug=True)

步骤2:前端main.js修改为异步请求

async function myFunction() {
    try {
        // 请求后端接口
        const res = await fetch('/api/get-data');
        const arr = await res.json();
        return arr;
    } catch (err) {
        console.error('获取数据失败:', err);
        return []; // 出错时返回空数组避免Plotly报错
    }
}

// 调用函数并加载到Plotly
myFunction().then(dataArr => {
    // 替换成你的Plotly配置
    Plotly.newPlot('plot-container', [{
        x: dataArr,
        type: 'line'
    }]);
});

方案2:前端直接读取静态txt文件

如果你的File.txt是静态资源,可以放到Flask的static文件夹下,前端直接通过fetch读取文件内容再解析成数组。

步骤1:放置文件

把File.txt放到Flask项目的static目录下(没有就新建一个)。

步骤2:前端main.js代码

async function myFunction() {
    try {
        // 读取静态txt文件
        const res = await fetch('/static/File.txt');
        const textContent = await res.text();
        // 解析文本为数组,根据你的txt格式调整分割规则
        const arr = textContent.split('\n').filter(line => line.trim());
        return arr;
    } catch (err) {
        console.error('读取文件失败:', err);
        return [];
    }
}

// 加载到Plotly
myFunction().then(dataArr => {
    Plotly.newPlot('plot-container', [{
        y: dataArr,
        type: 'bar'
    }]);
});
注意事项
  • 确保txt文件的路径正确:后端读取时注意服务器端的文件路径,前端请求时注意URL路径。
  • 处理异步逻辑:因为HTTP请求是异步的,必须用async/await或者.then()来处理返回的Promise,不能直接同步调用myFunction()拿到结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:47:13