当前位置: 首页 » 产品 » 商务广告 » 正文

如何使用node.js搭建服务器

放大字体  缩小字体 发布日期: 2024-09-29 07:28   来源:http://www.baidu.com/  作者:无忧资讯  浏览次数:31
核心提示:使用node搭建小型服务器(其实就是分析url然后输出文件给客户端)最近需要完成一个课程设计,被项目经理(组长)分配写界面,但

使用node搭建小型服务器(其实就是分析url然后输出文件给客户端)

最近需要完成一个课程设计,被项目经理(组长)分配写界面,但是总觉得只写前端的话缺了点什么,所以想自己写下后端玩一下。

期间还稍微纠结了一下用什么语言,本来打算正好学习一下PHP,可后来转念一想,用nodejs岂不美哉,不仅了解了后台开发,也相当于巩固了js基础,一举两得,美滋滋。

在学习node的过程中,学到了使用node实现一个服务器这一块,感觉是对前面所学模块的一个很好的总结。用到了四个基本的模块fs stream http path

代码如下:(内含蹩脚英文注释请见谅)

'use strict' var url=require('url'); var path=require('path'); var fs=require('fs'); var http=require('http'); //get the current path //var root=path.resolve('.');//以当前的目录为服务器的根目录 var root=path.resolve(process.argv[2] || '.');//以输入的参数作为服务器的根目录,如果没有输入参数就将当前目录作为服务器根目录 console.log('local root dir :' + root); //create server var server=http.createServer(function(request, response) { //get the path of URL var pathname=url.parse(request.url).pathname; //get the local path var filepath=path.join(root, pathname); //get the file stat and output the request file by callback function fs.stat(filepath, function(err, stat) { if(!err && stat.isFile()) { console.log('200' + request.url); response.writeHead(200); fs.createReadStream(filepath).pipe(response);//没有必要手动读取文件内容。由于response对象本身是一个Writable Stream,直接用pipe()方法就实现了自动读取文件内容并输出到HTTP响应。 } else { console.log('404' + request.url); response.writeHead(404); response.end('404 Not Found'); } }); }); server.listen(8080); console.log('Server is running at :8080/');

对于其中一些函数的解释:

path.resolve() 路径寻航(这名字不错) path.resolve([from…], to)

有个解释很有趣:相当于不断地调用系统的cd指令

eg:

path.resolve('foo/bar', '/tmp/file/', '..', 'a/http://www.jsgho.com/help/subfile') //相当于: cd foo/bar cd /tmp/file/ cd .. cd a/http://www.jsgho.com/help/subfile1 path.join([path1],path[2]...) 路径合并

将所有名称用path.seq串联起来,然后用normailze格式化

eg:

path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');=>'/foo/bar/baz/asdf'

既然提到了normalize

那么:

格式化路径 path.normalize(p)
将不符合规范的路径格式化,简化开发人员中处理各种复杂的路径判断

eg:

path.normalize('/foo/bar//baz/asdf/quux/..');=> '/foo/bar/baz/asdf'

http.response.end()结束相应,告诉客户端所有消息已经发送。当所有要返回的内容发送完毕时,该函数必须要被调用一次。如果不调用该函数,那么客户端将会永远处于等待状态。

使用方法:

response.end([data], [encoding])

data end()执行完毕后要输出的字符,如果指定了 data 的值,那就意味着在执行完 response.end() 之后,会接着执行一条 response.write(data , encoding);

encoding 对应data的字符编码

 
 
[ 产品搜索 ]  [ 加入收藏 ]  [ 告诉好友 ]  [ 打印本文 ]  [ 违规举报 ]  [ 关闭窗口 ]

 

 
推荐图文
推荐产品
点击排行
    行业协会  备案信息  可信网站