码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-03-19 13:25:02      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:运行   UNC   静态网页   引入   http   serve   write   dex   content   

Linux使用Node.js建立访问静态网页的服务实例详解
一、安装node.js运行所需要的环境。
二、创建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建立访问静态网页的服务实例详解

标签:运行   UNC   静态网页   引入   http   serve   write   dex   content   

原文地址:https://www.cnblogs.com/dwnnw/p/8601014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!