取这么一个标题,是因为实在想不起去什么名字 看网上的参考资料,ejs党和jade党势如水火Σ( ° △ °|||)︴ 但对于我等新手,暂时不想分心去了解模板引擎,专心于html不是挺好的嘛
—————————————————————————— 本文参考了Node.js实战的第二章,源码附在最后
首先看核心代码,目的是从缓存或者硬盘中读取html文件:
{ if (cache[absPath]) {//检查文件是否在缓存中sendFile(response, absPath, cache[absPath]);//从内存中返回文件 } else {fs.exists(absPath, (exists) {fs.readFile(absPath, (err) {send404(response);} else {cache[absPath] = data;//加入缓存中sendFile(response, absPath, data);//读取文件并返回}});} else {send404(response);}}); }}
send404和sendFile函数的实现
{ response.writeHead(404, {‘Content-Type’: ‘text/plain’}); response.write(‘Error 404: resource not found.’); response.end();} { response.writeHead(200,{“content-type”: mime.lookup(path.basename(filePath))} ); response.end(fileContents);}
接下来是创建服务器
filePath = false; if (request.url == ‘/’) {filePath = ‘public/index2.html’; } else {filePath = ‘public’ + request.url; } var absPath = ‘./’ + filePath; serveStatic(response, cache, absPath);});
运行一下,,应该是从csdn上扒下来的一篇博文
走过的路成为背后的风景,不能回头不能停留,若此刻停留,