AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JavaScript

Linux使用Node.js建立访问静态网页的服务实例详解

51自学网 http://www.wanshiok.com
Linux使用Node.js建立访问静态网页的服务,Linux中Node.js建立访问静态网页

Linux使用Node.js建立访问静态网页的服务实例详解

一、安装node.js运行所需要的环境,:/article/79536.htm

二、创建node目录(/node/www),并在目录下创建node.js服务文件server.js

var http = require('http');var fs = require('fs');//引入文件读取模块var documentRoot = ‘/node/www';//需要访问的文件的存放目录var server= http.createServer(function(req,res){  var url = req.url;   //客户端输入的url,例如如果输入localhost:9999/index.html  //那么这里的url == /index.html  var file = documentRoot + url;  console.log(url);//node/www/index.html     /*    file为文件路径    function为回调函数,    function的err为读取错误返回的信息,返回空就没有错误    function的data为读取成功返回的文本内容  */  fs.readFile( file , function(err,data){    if(err){      res.writeHeader(404,{        'content-type' : 'text/html;charset="utf-8"'      });      res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');      res.end();    }else{      res.writeHeader(200,{        'content-type' : 'text/html;charset="utf-8"'      });      res.write(data);//将index.html显示在客户端      res.end();    }  });}).listen(9999);console.log('服务器开启成功...');

三、创建index.html首页文件,放在路径为/node/www/下面

四、启动服务命令:node server.js

五、浏览器输入地址:http://localhost:9999/index.html

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


Linux使用Node.js建立访问静态网页的服务,Linux中Node.js建立访问静态网页  
上一篇:jQuery+ThinkPHP+Ajax实现即时消息提醒功能实例代码  下一篇:在 Angular 中实现搜索关键字高亮示例