JavaScript

超轻量级php框架startmvc

使用node.js搭建服务器

更新时间:2020-05-13 13:36:01 作者:startmvc
使用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 http://127.0.0.1:8080/');

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


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

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

eg:


path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
//相当于:
cd foo/bar
cd /tmp/file/
cd ..
cd a/../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的字符编码

以上所述是小编给大家介绍的使用node.js搭建服务器的方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对脚本之家网站的支持!

nodejs搭建服务器