gpt4 book ai didi

javascript - 在 Node.js 中运行 JS 文件

转载 作者:行者123 更新时间:2023-11-30 09:28:18 24 4
gpt4 key购买 nike

我是一名自学者,我在 Node.js 上运行测试文件时遇到问题。我正在使用以下命令:“Node ”。我不知道未定义文档是什么意思。在本例中,我输入的是 node test.js。你能帮忙的话,我会很高兴。我面临以下错误:

PS C:\Users\buddys\Desktop\Projects> node test.js
C:\Users\buddys\Desktop\Projects\test.js:8
document.write("Metri loves you too baby!");
^

ReferenceError: document is not defined
at Object.<anonymous> (C:\Users\buddys\Desktop\Projects\test.js:8:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:504:3

现在,当我运行 index.html 时,JavaScript 正在写入网页。这是我的索引和 .js 文件:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Learning</title>

</head>
<body>
<h1>JS for Metri</h1>
<p>blah blah blah</p>
<div class="content">

</div>

<!--place scripts at the bottom of the body unless big files. If it's a big files
Metri, make a separate .js file and link it to the HTML page by using src attribute. -->
<script src="test.js" charset="utf-8"></script>
</body>
</html>

测试.js

var youLikeMetri = true;
var age= 18;
var enter = 'You are permitted to be legally drunk';
var almost = 'You may legally smoke but not drink'
var exit= 'You are not permitted to be legally drunk';
//if statement if(condition){CODE BLOCK;}
if (youLikeMetri){
document.write("Metri loves you too baby!");
}
//COMPARISON OPERATORS
//==EQUAL TO !=NOT EQUAL TO !==NOT IDENTICAL
//>=GREATER THAN OR EQUAL TO ||OR
//<=LESS THAN OR EQUAL TO &&AND
if (age >= 21){
document.write(enter);
}
//elseif to create multiple conditions after first if.
else if(age <= 20){
document.write(almost);
}

else if (age < 18){
document.write(exit);
}
//while loops are continuous if the condition is met.
// while (condition){CODE BLOCK}
while (age <10) {
console.log('You are less than 10');
age++
//adds one to age when age is > 10 it will continue down.
}
document.write('You are older than 10 now')

最佳答案

document 不是标准 JavaScript 的一部分。它是网络浏览器提供的 API。

Node.js 不是网络浏览器,不提供 document 对象。

要从 Node.js 写入 STDOUT,您可以使用 process module .

process.stdout.write("Hello, world");

关于javascript - 在 Node.js 中运行 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47983335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com