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

前端 未结 2 348
借酒劲吻你
借酒劲吻你 2020-12-16 03:14

I need write some data in the file, using FS module (fs.writeFile). My stack is webpack + react + redux + electron.

The first problem was: Cannot resolve mod

相关标签:
2条回答
  • 2020-12-16 03:24

    In completion to the accepted answer.

    If you are using Webpack. Like when you are using Angular, React or other frameworks. require will be resolved by webpack. Which will screw it's usage at runtime.

    use window.require instead.

    Ex:

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

    Note: There is no need to use remote in order to access any of node api from a renderer process. As it's fully exposed.

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

    will do.

    Update

    Starting from v5 of Electron! The node api is no more exposed by default in the renderer process!!!

    the default for nodeIntegration flag changed from true to false.

    You can enable it when creating the Browser Window:

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

    The security risk of activating nodeIntegration

    nodeIntegration: true is a security risk only when you're executing some untrusted remote code on your application. For example, suppose your application opens up a third party webpage. That would be a security risk because the third party webpage will have access to node runtime and can run some malicious code on your user's filesystem. In that case it makes sense to set nodeIntegration: false. If your app is not displaying any remote content, or is displaying only trusted content, then setting nodeIntegration: true is okay.

    And finally !!!! The recommended secure way from the doc

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

    0 讨论(0)
  • 2020-12-16 03:29

    Problem is solved.

    Need use in electron app (where you add the bundle):

    var remote = require('electron').remote;
    var electronFs = remote.require('fs');
    var electronDialog = remote.dialog;
    
    0 讨论(0)
提交回复
热议问题