How to export specific data from a Javascript file to Node.js file?

Viewed 43
// index.js
let intro = document.getElementById('intro');
let name = "Harry";
module.exports = name;
    
// new.js
let name = require("./index.js");
console.log(name);

I am trying to build an application with Node.js. When I want to export a string or specific data with module.exports to use it in the new.js file, an error is logged in the console saying that "document is not defined". All I need is to export a variable having a string to my Node.js (new.js). Also my index.js have multiple document.getElements. I also noticed that when I remove document.getElements then I successfully import that data from index.js without any error. How could I export data from index.js file with that document.getElement present in that?

1 Answers

Your issue is with document.getElementById() as in Node.js the browser DOM API is not defined.

So the first line of the index.js module is failing, and you can't reach the module.exports line.

UPDATE

To postpone the evaluation of the offending code, one solution can be to wrap the code in a function, that can be exported as well and run just when the file is inside a browser.

here the example:

// index.js
function myGetElementBy(d, selector) {
    let intro = d.getElementById(selector);
}

let name = "Harry";
module.exports = {
 name,
 myGetElementBy,
};

// new.js
let {name, myGetElementBy} = require("./index.js");
console.log(name);

if (window && 'document' in window) {
   myGetElementBy(document, 'intro')
}

Now the module is exporting an object that contains the function other than the variable name.

Related