cannot manipulate dom object after nodejs require statement - javascript

I am trying to learn nodejs and I cannot manipulate DOM object after using the require statement in server.js file. However, it works fine without it. When I click on the paragraph in the browser it would not change. Does anyone know why?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p id="demo">Click me to change my HTML content (innerHTML)</p>
<script src="server.js"></script>
</body>
</html>
server.js
var config = require('./config');
document.addEventListener('DOMContentLoaded', function() {
$("#demo").click(function () {
document.getElementById("demo").innerHTML = "Paragraph changed!";
})
});

If you are running your server file using node, document is not going to reference your browser. Your browser is unavailable to Node. Only front-end javascript is going to be able to reference the DOM. In addition, using require in front-end javascript should throw an error if you're not using some bundler such as browserify and therefore the following jQuery code will not run. Open up your browser's developer tools and you should see an error in the console.
Node is not meant to work with the DOM and server files shouldn't be inserted into your HTML. Keep your server code separate from your front-end code. Node is meant to set up servers and serve up files, not to work with the DOM. Try reading more about Node and what it's used for, and maybe do a few tutorials to get familiar with it.

Open the html in the browser, consle say require is not defined
at server.js:1. In html script not support the require syntax

Related

window.np is undefined even though it appears in console when window is printed

I've been trying to fix this one issue I ran into but have no idea why my code is wrong. I have this module I made using javascript for NPM. I just converted that npm to HTML syntax and imported that module into this HTML file.
But when I try to access the items using "window.np"(window is how I save those files into the user's computer), it says "window.np" is undefined. I have no idea why it says this because when I just do console.log(window), I can see 'np' as one of the attributes. But I am still unable to access it.
This is the output when I do "console.log(window)".
This is the expanded version of the picture above.
<!DOCTYPE html>
<html>
<body>
<script type="module" src="https://unpkg.com/numpy-matrix-js#1.1.0/src/html/index.js">
</script>
<script>
console.log(window)
console.log(window.np)
</script>
</body>
</html>
Scripts included as an ES6 module via type="module" are actually deferred by default (MDN), meaning that the numpy-matrix-js script will run after the inline script.
The fix for this is simple: you need to defer the inline script's execution to after the module's. One way is the defer attribute, but since that only works on external scripts, you'll need to put it in a separate file. The other method would be to listen for DOMContentLoaded:
<!DOCTYPE html>
<html>
<body>
<script defer type="module" src="https://unpkg.com/numpy-matrix-js#1.1.0/src/html/index.js">
</script>
<script>
window.addEventListener("DOMContentLoaded",function(){
console.log(window)
console.log(window.np)
});
</script>
</body>
</html>
See How to defer inline Javascript? for more info.
As for why it displays in the console, I'm guessing that the fancy object browser looks up the properties when you click on it (ie. after the module has ran), not when its logged.

Correct way of importing in javascript while using Flask

I just started JavaScript. I wrote some code with javascript using the library: Three.js, now I wanted to do the Backend with Python. Therefore i started using Flask.
So I have my index.html in the templates directory, inside my index.html i call my script.js like this:
<script type="module" src="/static/script.js"></script>
In my script.js I import three.js in the beginning like this:
import "/three.js"
The Three.js file is in the same static folder. But somehow the import doesnt work when i use Flask.
First of all, the 'import' statement hasn't yet widely supported by browsers, so if you really want to use it, you have to use a module bundler e.g. webpack, broswerify, to wrap all files into one big js file. However, if you are not familiar with those tools, to be honest, you have to spend many time to learn how to use them.
So I recommend you to keep things simple. For example, you can first make a copy of the library's source code and save it to your project's static folder, so that it can be served publicly. Second, you can create a HTML file, with following template:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<script src="/static/three.js"></script>
<script src="/static/script.js">
</body>
</html>
P.S. this example is from Three.js offical document, with a little modification.
Since all scripts in a HTML share a same global environment, after the first <script> tag is loaded, the code in the next <script> tag can access three.js's global variable that is loaded before!
flask is mirco framework, so you need to follow the documentation instruction on using static files.
have a look on this post
where to keep js files in Flask applications?

javascript require doesn't work inside html

I'm writing html code that involves js code. Below a simple example:
<!DOCTYPE html PUBLIC >
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello JavaScript!" into an HTML element with id="demo":</p>
<p id="demo"></p>
<script>
var net = require('net');
var sleep = require('sleep');
var element = document.getElementById("demo");
element.innerHTML = "Hello JavaScript!";
sleep(1)
</script>
Unfortunately "Hello JavaScript!" doesn't appear when I browse the above file with my browser. Looking inside the debug console I can see the folowing message:
ReferenceError: require is not defined
So it seems that require is not defined inside the html code but I've written a small test.js file as below:
var net = require('net');
var sleep = require('sleep');
sleep.sleep(1)
and then I run it with
node test.js.
No errors, everything works fine, require is available and sleep and net as well. Why the code inside html file doesn't work?
Javascript is not the same as node.js
require() is not a part of JavaScript standard and is not supported by browsers out of the box, it is the node.js module system.
You might need to directly include the modules; some of the modules might not work in the browser sandbox context.
Also, tools such as http://browserify.org/ might be useful.
The reason you are getting ReferenceError: require is not defined is because nowhere in your html page is Require included. Require does not come with your standard JavaScript library. You must include the file on your page so it can be loaded and used.
This can be done by simply adding <script src="myJS.js"></script> in the <head> or <body> tags. The myJS.js file will, of course, be replaced by the require.js file.
The reason it works when you run with node is because Node already has its own module loader.

Using Document object in nodejs

I'm still new to javascript and node.js and was trying to accomplish something but I am encountering the error ReferenceError: Document not defined
Given the following code in seperate files:
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Test Website</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p id="para1"> Some text here</p>
</body>
</html>
And script.js:
function getParagraphContents() {
var paragraph = document.getElementById("para1");
var temp = paragraph.textContent;
console.log(temp);
}
So my problem being is I wanted to be able to run the command node script.js from the command line but keep getting an error message. I keep reading other answers and documentation but nothing seems to be the right answer. Any suggestions? P.S. I am using terminal on mac osx and have node and npm install correctly.
Thank you.
script.js is a script designed to run in a browser, not in node.js. It is designed to operate on the current web page and uses the document object to get access to that page.
A node.js execution environment is not the same as a browser. For example, there is no notion of the "current page" like there is in a browser and thus there is no global document or window object either like there is in a browser.
So, this all explains why trying to run node script.js doesn't work. There's no global document object so your script quickly generates an error and exits.
We can't really tell from your question if you just don't really understand the difference between running scripts in a browser vs. running scripts in a node.js environment and that's all you need to have explained or if you actually want to operate on an HTML document from within node.js?
It is possible to operate on HTML pages from within node.js. The usual way to do that is to get an HTML parsing library like jsdom. You can then load some HTML page using that library and it will create a simulated browser DOM and will make things like the document object available to you so you could execute a browser-like script on an HTML document.

Automatically embed a stylesheet in HTML

I'm building out error pages (404/503) which need to be standalone html files, my server-side is nodejs, but these files will be hosted directly in nginx. I'm trying to automatically embed a stylesheet at the top of a html document and was wondering whether there are any tools for this purpose. Searching on stack overflow and google keeps returning tools to inline css for use in emails, but that is not what I want.
I would like to start out with
before.css
.body { color: black }
before.html
<!DOCTYPE html>
<html>
<head>
<title>A Question</title>
<link rel="stylesheet" href="before.css">
</head>
<body>
<p>Here be the answer</p>
</body>
</html>
Which once the process is complete I would end up with
after.html
<!DOCTYPE html>
<html>
<head>
<title>A Question</title>
<style>.body { color: black }</style>
</head>
<body>
<p>Here be the answer</p>
</body>
</html>
The ideal solution would be a gulp plugin or an idea of how to write one.
I can write this in JS if needed. Also I'm already using EJS and Stylus to derive the original before files.
Many thanks
As many commented, you're trying to find a solution to a very complex problem and there are probably many easy to use workarounds for this. But if you really want to do this then here are a few approaches I think best:
Server-side Templates:
The best, clean and straightforward method of embedding a stylesheet into HTML is to use a server-side scripting language (as #Mr_Green pointed out). There are many to chose from, and as you're using Node.js, the best library would be EJS or Jade. You can also use PHP, Ruby, Python or whatever you think best, but the idea is same:
First, you need to read the contents from the stylesheet and store it in a variable. In Node.js you can use the fs.readFile() to easily read the contents of the .css file.
Then, you have to output the contents of the .css file (stored in a variable) into your HTML. With EJS for example, if the contents of your CSS file is in a variable styleFile, then you can do <style><%= styleFile %></style> to directly put the contents of your stylesheet into your HTML <style> tag.
Using Ajax with JavaScript:
Another solution would be to use Ajax and get the contents of your stylesheet and then use JavaScript to simply put it inside your <style> tag. For example with some jQuery you could do: $("style").html(// stylesheet contents var);.
Of course you can also use Haml, if that helps.
Hope that answers your question.

Categories