我是计算机科学的新手,我喜欢编程。所以我开始学习nodejs并在test.js中编写了这个简单的代码..
var http = require("http");
var fs=require('fs');
var path=require('path');
var msg= "hi\nhow r u ?\nfine";
var file='textms.txt';
http.createServer(function (req,res){
fs.open(file,function(exists){
if(exists){
fs.open(file,msg,function(err){
if(err)throw err;
});
}else{
fs.writeFile('test.txt',msg);
console.log('New file is created : ');
}
});
res.end();
}).listen(8080);
console.log('server running on port 8080');
这是我的index.html页面代码..
<html>
<head>
<title>
Chat Test With Nodejs
</title>
<script type="text/javascript" src="test.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div id="cnt"></div>
<input type="text" class="text">
<button id="btn">Send</button>
</body>
</html>
我在 chrome(localhost:8080) 上运行此代码。效果很好。
问题:当我在 Chrome 上运行 index.html
页面时,我在 Chrome 控制台中收到此错误:
Uncaught ReferenceError: require is not defined @ server.js:1
我尝试在谷歌上搜索,但没有找到任何有用的东西。 问题:为什么我会收到此错误?
最佳答案
看起来您对 Node 还很陌生。要回答您的问题,您不会在index.html 中运行服务器文件。你的服务器文件是运行你的index.html....有点。
我不会对 Node 的工作原理进行很长的解释,而是向您提供这个资源,NodeSchool 。可能是开始学习 Node 的最佳地点之一。
祝您好运,如果您有任何疑问,请随时与我们联系。
谢谢
关于javascript - 无法在索引页中运行 Node 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400510/