Ad

Electron / Node - Snipppets Using Require And ReadFile Makes Javascript Fail

I use Electron which uses NodeJS. I started with a single very long HTML file. Now I want to split it up, similar to PHP require. I managed to do so with require and readFile.

However after using this approach my javascript stopped working. My guess is that my whole approach is wrong.

Inline script

const fs = require('fs');
require('./assets/js/snippets.js');

snippets.js

function snippet(name) {
  fs.readFile('snippets/' + name + '.html', function (err, data) {
    document.querySelector('[snippet-' + name + ']').innerHTML = data.toString();
  });
}

snippet('header');
snippet('post');
snippet('footer);

What is the correct way to do this? Can I use the built in functions or do I need an exernal library?

Ad

Answer

readFileSynccan be used instead of readFile.

https://stackoverflow.com/a/56110224/148496

Ad
source: stackoverflow.com
Ad