Home > Software design >  JS Script using DOM running on pm2 server
JS Script using DOM running on pm2 server

Time:03-28

I have read that serverside, you cant use DOM. I've created a web application using DOM and I wonder what needs to be done to reproduce this code to make it work on a server, so the people on the internet can work with it. Here is a little peak of a code:

// Listen for export button click
document.getElementById('exportForm').addEventListener('submit', function (e) {
    setTimeout(exportData, 20);
    e.preventDefault();
});

// Export data function
function exportData(e) {
    console.log("Exporting...");

    // device details and time range details
    const devId = (document.getElementById('deviceInput')).value;
    var dateFrom = (document.getElementById('dateFromInput')).value;
    var dateTo = (document.getElementById('dateToInput')).value;
    var timeFrom = (document.getElementById('timeFromInput')).value;
    var timeTo = (document.getElementById('timeToInput')).value;
    const limit = (document.getElementById('limitInput')).value;
    const key = (document.getElementById('keysInput')).value;

When I try to run it on server using pm2 start app.js, it returns this error:

ReferenceError: document is not defined
    at Object.<anonymous> (/home/cloud/sites/App/app.js:6:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)

I've heard about JSDom, but I think there needs to be html included in a string and then I have no idea how to connect the css in there and so on. Is there a better way for me to make this work?

CodePudding user response:

Document object is a browser feature hence you cant use it inside server, Instead you have other features like the FS (File System)

Anyhow using JSDom may be possible, you have to rewrite using inline styles https://www.codecademy.com/article/html-inline-styles which is not a good practice and you should avoid it

  • Related