Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...