【问题标题】:Alternative for fs.readFile when targeting the web using webpack使用 webpack 定位 web 时 fs.readFile 的替代方案
【发布时间】:2018-09-29 03:57:18
【问题描述】:

在我的 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.

我想知道在为 web 打包时,我可以使用哪种方法来加载“服务器”文件而不是本地文件的内容(即使我目前正在本地测试)。

【问题讨论】:

  • 您是否考虑过为您要打包的特定文件类型使用 webpack 加载器?例如:npmjs.com/package/text-loader
  • @Mark_M 我不打算将文本文件的内容(例如)打包到 webpack 包中,并且希望能够动态加载应用程序附带的请求文件。

标签: javascript node.js web webpack fs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      相关资源
      最近更新 更多