如何将 .js 文件中的 js 变量传递到 Electron 中的 .html 页面?

Dan*_*nev 2 javascript electron

我是第一次开发电子应用程序。我在 .js 文件中使用函数来查找文件夹中的所有文件并将它们全部写入控制台。

fs.readdir(save_path, function(err, files) {
    if (err) {

    } else {
       for(let projectFile of files)
       {
           fs.readFile(save_path+"\\"+projectFile, function(err, data)
           {
                if(data != null)
                {
                    console.log(projectFile);
                }
            });
       }
    }
});
Run Code Online (Sandbox Code Playgroud)

但是有没有办法将这个projectFile变量发送到 html 页面?因为有 for 循环,所以我猜我也需要在 html 中使用 for 循环。

<div class="col-sm-3 text-center" style="background: #34495e; height:2160px;">
        <p class="b wh" style="margin-top: 15%;">Latest projects</p>
        <!-- Projects should be displayed here. I guess there should be some kind of for loop -->
        <hr class="divider">
    </div>
Run Code Online (Sandbox Code Playgroud)

谢谢!

slo*_*k2k 7

一种同步解决方案是使用共享对象,如

// within main.js
var entries = fs.readdirSync(save_path+"\\"+projectFile);
global.sharedObj =  { entries : entries };
// before 
app.on('ready', function() ...
Run Code Online (Sandbox Code Playgroud)
<div class="col-sm-3 text-center" style="background: #34495e; height:2160px;">
    <p class="b wh" style="margin-top: 15%;">Latest projects</p>
    <script>
      const {remote} = require('electron');
      const entries = remote.getGlobal('sharedObj').entries;
      for (var i in entries) {
         document.write('<p>' + entries[i] + '</p>');
      }
     </script>
      <hr class="divider">
  </div>
Run Code Online (Sandbox Code Playgroud)

或者您可以通过 ipcMain 和 ipcRenderer 使用消息传递来异步执行。