如何在 Electron.Atom\WebPack 应用程序中使用 FS 模块?

How to use FS module inside Electron.Atom\WebPack application?

我需要在文件中写入一些数据,使用 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不为空

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

问题已解决。

需要在 electron 应用程序中使用(添加包的地方):

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

除了已接受的答案。

如果你正在使用Webpack(比如当你使用Angular、React或其他框架时)require将由[=14=解决],这将在 运行 时搞砸它的使用。

改用window.require

例如:

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

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

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

会做。

更新

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

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

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

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

激活nodeIntegration的安全风险

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

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

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