简体   繁体   中英

How to pass js-variable from .js file to .html page in Electron?

I'm developing electron app for the first time. I use function in .js file to find all files in folder and to write all of them to console.

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);
                }
            });
       }
    }
});

But is there any way to send this projectFile variable to html page? Because there is for loop, so I need to use for loop in html too I guess.

<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>

Thank you!

One sync solution would be using a shared object like

// within main.js
var entries = fs.readdirSync(save_path+"\\"+projectFile);
global.sharedObj =  { entries : entries };
// before 
app.on('ready', function() ...
<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>

Or you can use messaging via ipcMain and ipcRenderer to do it async.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM