问题描述
我对javascript和node.js还是陌生的,正在尝试完成一些工作,但是遇到了ReferenceError:未定义文档错误
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:
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>
和script.js:
And script.js:
function getParagraphContents() {
var paragraph = document.getElementById("para1");
var temp = paragraph.textContent;
console.log(temp);
}
所以我的问题是我希望能够从命令行运行命令node script.js
,但始终收到错误消息.我一直在阅读其他答案和文档,但似乎没有什么是正确的答案.有什么建议? P.S.我在Mac OS X上使用终端,并正确安装了节点和NPM.
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.
谢谢.
推荐答案
script.js
是一个旨在在浏览器中运行的脚本,而不是在node.js中运行.它旨在在当前网页上运行,并使用document
对象来访问该页面.
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.
node.js执行环境与浏览器不同.例如,没有浏览器中的当前页面"概念,因此也没有浏览器中的全局document
或window
对象.
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.
因此,所有这些都解释了为什么尝试运行node script.js
无效的原因.没有全局document
对象,因此您的脚本会快速生成错误并退出.
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.
我们不能从您的问题中真正看出您是否真的不了解在浏览器中运行脚本与在node.js环境中运行脚本之间的区别,而这仅是您需要说明的,或者想在node.js中处理HTML文档吗?
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?
可以在node.js中对HTML页面进行操作.通常的方法是获取一个像jsdom这样的HTML解析库.然后,您可以使用该库加载一些HTML页面,它将创建一个模拟的浏览器DOM,并使诸如document
对象之类的内容可供您使用,以便您可以在HTML文档上执行类似浏览器的脚本.
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.
这篇关于在Node.js中使用Document对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!