【问题标题】:How to use FS module inside Electron.Atom\WebPack application?如何在 Electron.Atom\WebPack 应用程序中使用 FS 模块?
【发布时间】:2016-10-25 22:54:17
【问题描述】:

我需要在文件中写入一些数据,使用 FS 模块 (fs.writeFile)。我的堆栈是 webpack + react + redux + electron。

第一个问题是:无法解析模块“fs”。 我尝试使用

target: "node",
---
node: {
    global: true,
    fs: "empty",
}
---
resolve: {
    root: path.join(__dirname),
    fallback: path.join(__dirname, 'node_modules'),
    modulesDirectories: ['node_modules'],
    extensions: ['', '.json', '.js', '.jsx', '.scss', '.png', '.jpg', '.jpeg', '.gif']
},

经过多次尝试,问题得到解决(node: {fs: "empty"})。但随后出现了第二个问题:screenshot

//In method componentDidMount (React)
console.log('fs', fs);
console.log('typeOf', typeof fs.writeFile);

//By clicking on the button
console.log(fs);
console.log(typeof fs.writeFile);

可以看到,fs是空对象,不存在writeFile方法。我试图改变 webpack 的配置。

const path = require('path');
const fs = require('fs');
const webpack = require("webpack");
console.log(fs);

在这种情况下 fs 不为空。

如何解决这个问题?有什么想法吗?

【问题讨论】:

    标签: javascript node.js reactjs npm electron


    【解决方案1】:

    问题解决了。

    需要在电子应用程序中使用(添加捆绑包的地方):

    var remote = require('electron').remote;
    var electronFs = remote.require('fs');
    var electronDialog = remote.dialog;
    

    【讨论】:

    • 您是否将其添加到您的主 Electron 进程(即 main.js)中?我添加了这些定义,但不知道如何处理它们......
    • 请务必阅读electron.remote:“在Electron中,与GUI相关的模块(如对话框、菜单等)仅在主进程中可用,在渲染器进程中不可用。在为了从渲染器进程中使用它们,ipc 模块是必要的,可以将进程间消息发送到主进程。使用远程模块,您可以调用主进程对象的方法,而无需显式发送进程间消息"
    【解决方案2】:

    除了接受的答案。

    如果你使用 Webpack(比如当你使用 Angular、React 或其他框架时)require 将被 webpack 解析,这将在运行时破坏它的使用。

    请改用window.require

    例如:

    var remote = window.require('electron').remote;
    var electronFs = remote.require('fs');
    var electronDialog = remote.dialog;
    

    注意:无需使用远程来从渲染器进程访问任何 Node API,因为它已完全公开。

    const fs = window.require('fs');
    const path = window.require('path');
    

    会的。

    更新

    从 Electron v5 开始,Node API 不再默认暴露在渲染器进程中!

    nodeIntegration 标志的默认值从 true 更改为 false

    您可以在创建浏览器窗口时启用它:

    app.on('ready', () => {
        mainWindow = new BrowserWindow({
            webPreferences: {
                nodeIntegration: true, // <--- flag
                nodeIntegrationInWorker: true // <---  for web workers
            }
        });
    });
    

    激活nodeIntegration的安全风险

    nodeIntegration: true 仅当您在应用程序中执行一些不受信任的远程代码时才会存在安全风险。例如,假设您的应用程序打开了第三方网页。这将是一个安全风险,因为第三方网页将有权访问节点运行时并且可以在您用户的文件系统上运行一些恶意代码。在这种情况下,设置nodeIntegration: false 是有意义的。如果您的应用没有显示任何远程内容,或者仅显示受信任的内容,那么设置nodeIntegration: true 是可以的。

    最后,文档中推荐的安全方式:

    https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 2017-02-20
      • 2014-02-20
      • 1970-01-01
      • 2017-01-06
      • 2017-04-15
      • 2016-08-23
      • 2021-05-04
      • 2017-01-08
      相关资源
      最近更新 更多