Generating a website in Node.js
A code example.
Published on: Jun 6, 2025, 6:05 PM CET Updated on: Jun 6, 2025, 6:40 PM CET
Share

LibreBlog.org provides a text editor for editing the contents of your website and a database interface for managing it. However, you can generate your website from a JSON object, which has the advantage of being easily manipulated.

In this example, we are using a copy of a website's database in JSON format. It can be generated by clicking on the "Download" button under "Download a copy of the database in JSON format" on the Settings section of our CMS.

Here's a step-by-step guide to generating your website using Node.js:

  • Create a folder (you can name it, for example: node_test).
  • Inside this folder, run: npm install libreblog.
  • Inside the folder, place the copy of the website database in JSON format. If necessary, change the file name to mydb.json.
  • Still inside the folder, create a file called index.mjs with the content shown below. Then run: node index.mjs.
							
import libreblog from 'libreblog';
import http from 'http';
import fs from 'fs';

let webFolder; //public_html folder

const readJsonFile = function (filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

const initLibreblog = async function() {
  await libreblog.importModules();
  await libreblog.startDb();

  libreblog.useSqlite(async (db) => {
    const jsonData = await readJsonFile('./mydb.json');
    await libreblog.createTables(db);
    await libreblog.restoreDbFromJson(jsonData);
    await libreblog.updateSettings();
    webFolder = await libreblog.createWebsiteFolder(db, false);

    server.listen(1234, () => {
      console.log('Go to http://localhost:1234/index.html');
    });
  });
}

const server = http.createServer(async (req, res) => {
  if (req.method === 'GET') {
    try {
      const file = webFolder.getFile(req.url.substring(1));
      res.end(file.contents);
    } catch (error) {
      res.writeHead(500, { 'Content-Type': 'text/plain' });
      res.end('Error reading file: ' + error.message);
    }
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not supported');
  }
});

initLibreblog();

						

Notes

  1. In this example, we are not serving media files (images).
  2. Uncheck the "Remove '.html' from page URLs" option in Settings before generating a copy of the website database.