用node.js做一个服务器

  1. 创建server.js文件
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号?\nnode server.js 8888 例如这样?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var path = request.url 
  var query = ''
  if(path.indexOf('?') >= 0){ query = path.substring(path.indexOf('?')) }
  var pathNoQuery = parsedUrl.pathname
  var queryObject = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/













  console.log('得到 HTTP 路径\n' + path)
  console.log('查询字符串为\n' + query)
  console.log('不含查询字符串的路径为\n' + pathNoQuery)
if(path=='/style'){
    response.setHeader('Content-Type','text/css;charset=utf-8')
    response.write('body{background-color:#ddd;color:#666}')
    response.end()
}else if(path == '/script'){
    response.setHeader('Content-Type','text/javascript;charset=utf-8')
    response.write('alert("这是js执行的")')
    response.end()
}else if(path=='/'){
    response.setHeader('Content-Type','text/html;charset=utf-8')
    response.write('\n'+
    ''+
    ''+
    '

你好Hello Node.js

') response.end() }else{ response.statusCode = 404 response.end() } /******** 代码结束,下面不要看 ************/ }) server.listen(port) console.log('监听 ' + port + ' 成功\n http://localhost:' + port)
  1. 命令行
    node server.js 8888node server 8888指定端口号
    新开命令行窗口
curl -s -v -- "http://127.0.0.1:8888"
curl -s -v -- "http://127.0.0.1:8888/index"
curl -s -v -- "http://127.0.0.1:8888/index=?sddfsdfsdf"

查看结果
ps:打印出现%时,如Hi%,编辑server.js文件,Hi\n,保存退出。再次执行node server.js 8888node server 8888指定端口号,新开命令行窗口

curl -s -v -- "http://127.0.0.1:8888"
curl -s -v -- "http://127.0.0.1:8888/index"
curl -s -v -- "http://127.0.0.1:8888/index=?sddfsdfsdf"

打印查看结果即可

你可能感兴趣的:(用node.js做一个服务器)