Home > Back-end >  Proper method of importing functions
Proper method of importing functions

Time:12-04

After some very helpful tips learning about javascript promises and how they behave, I am looking for some help with properly importing/exporting functions from one javascript file into another which is run via NodeJS.

Essentially I want basicNode.js to open an html doc, and then once that is open (and the promise implied via the open(html) statement is 100% complete/finalized) run the function from change.js to alter the html to show "Hello" in the place of "Welcome to JavaScript". This will provide proof of concept that can then be extrapolated for a project dealing with automating reports at my internship, so any help is greatly appreciated

basic.html

<!DOCTYPE html>
<html>  
<head>  
</head>  
<body>
<p>Date/Time: <span id="datetime"></span></p>
  
<p id="here">Welcome to JavaScript</p>  
<form>  
<input type="button" value="click" onclick="changeThis()"/>  
</form>  
</body> 
<script>
var dt = new Date();
    document.getElementById("datetime").innerHTML = dt.toLocaleString();
</script>
<script type="text/javascript" src="change.js"></script> 
<!--
<script>waitForElementToDisplay("#here",function(){alert("Hi");},1000,9000);</script> 
--> 
</html> 

change.js

function changeThis() {
    document.getElementById("here").innerHTML = "Hello";
}

module.exports={changeThis};

basicNode.js

const open = require('open');
var { change }  = require('./change')
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.document = new JSDOM('./basic.html').window.document;

const main = async () => {
  await open('./basic.html');
  change.changeThis();
}

main();

CodePudding user response:

In your change.js-file you are exporting your function as a named export. A named export is normally used if you are only exporting one function from a file (this is not a rule), and named exports are mainly used when you are exporting several functions from a file.

This is a named export

module.exports= { changeThis };

A named export is imported as

var { changeThis }  = require('./change')

The opposite to a named export is a default export.

module.exports = changeThis

This is imported as

var changeThis = require("./change")

Edit: If what you want is to read the file, moodify the DOM and then write it to a file again, then you can do it like this.

const jsdom = require('jsdom');
const { JSDOM } = jsdom;

// Read the file from the system
const fs = require('fs');
const html = fs.readFileSync('./basic.html');

// Create a jsdom and modify the file
const dom = new JSDOM(html);
dom.window.document.getElementById('here').innerHTML = 'Hello';

// write the file to disc
fs.writeFileSync(
    './basicUpdated.html',
    dom.window.document.documentElement.outerHTML
);
  • Related