nodejs在服务器的安装

nodejs在服务器的安装

node安装

yum install nodejs
注意,缺少组件就用npm install安装

随便写个小程序

var http = require('http');
var fs = require('fs');
var url = require('url');

//创建服务器
http.createServer(function(request,response) {
  //解析请求,包括文件名
  var pathname= url.parse(request.url).pathname;
  //输出请求的文件名
  console.log("Request for "+ pathname + "  received.");
  //当请求static文件夹时,设置文件返回类型是text/css
  var firstDir = pathname && pathname.split('/')[2];
  var ContentType = null;
  if (firstDir && firstDir === 'js') {
    ContentType = {'Content-Type': 'application/javascript'};
  } else {
    ContentType = {'Content-Type': 'text/html'}
  }

  //从文件系统中去请求的文件内容
  fs.readFile(pathname.substr(1),function(err, data) {
    if(err) {
      console.log(err);
      //HTTP 状态码 404 : NOT FOUND
      //Content Type:text/plain
      response.writeHead(404, {'Content-Type': 'text/html'});
    }
    else {
      //HTTP 状态码 200 : OK
      //Content Type:text/plain
      response.writeHead(200, ContentType);

      //写会回相应内容
      response.write(data.toString());
    }
    //发送响应数据
    response.end();
  });
}).listen(2366);

后台执行

nohup node index.js &

posted @ 2022-06-06 23:21  陆敏技  阅读(292)  评论(0编辑  收藏  举报
Web Counter
Coupon for Contacts