起服务的代码:
var http = require('http');
var fs = require('fs');
var path = require('path')
var mime =require('mime');
var cache = {};
//所请求的文件不存在时发送404错误
function send404(response){
response.writeHead(404,{'Conten-Type': 'text/plain'});
response.write('Error 404 : resource not found');
response.end();
}
//提供文件数据服务
function sendFile(response,filePath,fileContents){
response.writeHead(
200,
{
'Content-Type':mime.getType(path.basename(filePath))
}
);
response.end(fileContents);
}
//判断文件是否被缓存
function serverStatic(response,cache,absPath){
console.log(cache)
if(cache[absPath]){
console.log(cache[absPath]);
sendFile(response,absPath,cache[absPath]);//从内存中返回文件
}else{
fs.exists(absPath,function(exists){
if(exists){
fs.readFile(absPath,function(err,data){//从硬盘中读取文件
if(err){
send404(response);
}else{
cache[absPath] = data;
sendFile(response,absPath,data);//从硬盘中读取文件并返回
}
})
}else{
send404(response);
}
});
}
}
var server = http.createServer(function(req,res){
var filePath = false;
var webPage = fs.readFileSync('../html/webpage.html');//同步读取
if(req.url == '/'||req.url=="/favicon.ico"){
filePath = '../js/webpage.js'
}else{
filePath = '../'+req.url;
}
var absPath = filePath;//./static/js/webpage.js
console.log(absPath);
res.write(webPage);
serverStatic(res,cache,absPath);
res.end();
})
server.listen('3000',function(err){
if(err){
console.log(err);
throw err;
}
console.log('服务器已开启');
})
渲染页面的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="Content-type:application/x-javascript" href="../css/webpage.css">
</head>
<body>
<div class="clearfix wrapper">
<p class="storeTitle">商城</p>
</div>
<script src="../js/webpage.js" type="text/javascript"></script>
</body>
</html>
引用的webpage.js代码:
var screenheight =window.innerHeight;
var wrapper = $('.wrapper');
报错信息: