使用 webpack 定位网络时 fs.readFile 的替代方案

Alternative for fs.readFile when targeting the web using webpack

在我的 Electron 应用程序中,我正在使用 fs.readFile 读取一些应用程序文件(不是用户文件,而是 Electron 应用程序根目录中的实际文件),但是在为 web 打包时这显然不起作用。或者我尝试按照以下方式实现一些东西:

function loadFile(filePath: string) {
    let result = null;
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filePath, false);
    xmlhttp.send();
    if (xmlhttp.status === 200) {
        result = xmlhttp.responseText;
    }
    return result;
}

不幸的是,我遇到了以下异常:XMLHttpRequest cannot load file:///[...]/Testfile.txt. Cross origin requests are only supported for HTTP.

我想知道在为网络打包时我可以使用哪种方法来加载 "server" 文件的内容而不是本地文件(即使我目前正在本地测试)。

我的解决方案不起作用,因为我在浏览器中本地打开了应用程序,因此请求协议是 file://。为了能够调试它,我安装了 serve 并启动了一个本地服务器来测试应用程序。

你的问题得到解答了吗? 如果不。试试这个:

if (xmlhttp.status === 200 || xmlhttp.status === 0) {
    result = xmlhttp.responseText;
}