Node.js开发手册(二)
2013-05-27 21:17
218 查看
Node.js开发手册(二)
作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs一、静态文件服务
如果我们想把磁盘上的文件作为Web内容对外提供服务,那么怎么用Node来实现呢?答案是使用fs模块。我们可以使用fs即filesystem模块载入文件的内容,并把内容通过createServer回调函数传递出去。提供静态文件服务是Node.js的核心基础功能,应该掌握它。
二、Demo
下面我们创建三个文件,这些文件都会由NodeJS提供静态文件服务。1. index.html
内容如下:<html> <head> <title>Yay Node!</title> <link rel="stylesheet" href="styles.css" type="text/css" /> <script src="script.js" type="text/javascript"></script> </head> <body> <span id="yay">Yay!</span> </body> </html>
2. script.js
内容如下:// script.js window.onload=function(){ alert('Yay Node!'); };
3. styles.css
内容如下:#yay{ font-size: 5em; background: blue; color: yellow; padding: 0.5em; }
将上面的三个文件放入content目录下。
4. 编写Node程序
创建名为server.js的脚本文件,内容如下:var http = require('http'); var path = require('path'); var fs = require('fs'); http.createServer(function(req, res){ var lookup = path.basename(decodeURI(req.url)) || 'index.html', f = 'content/' + lookup; fs.exists(f, function(exists){ console.log(exists ? lookup + " is there" : lookup + " doesn't exist"); }); }).listen(8080);
用supervisor热部署工具执行以上程序:
$ supervisor server.js
在浏览器访问地址:http://localhost:8080/foo
终端显示:
DEBUG: Starting child process with 'node server.js'
foo doesn't exist
在浏览器访问地址:http://localhost:8080/index.html
终端显示:
DEBUG: Starting child process with 'node server.js'
DEBUG: Watching directory '/home/chszs/tmp' for changes.
index.html is there
三、进阶
假定我们想让客户端知道文件的类型,可以通过扩展名进行判断。修改server.js文件,内容为:
// server.js var http = require('http'); var path = require('path'); var fs = require('fs'); var mimeTypes = { '.js': 'text/javascript', '.html': 'text/html', '.css': 'text/css' }; http.createServer(function(req, res){ var lookup = path.basename(decodeURI(req.url)) || 'index.html', f = 'content/' + lookup; fs.exists(f, function(exists){ if(exists){ fs.readFile(f, function(err, data){ if(err){ res.writeHead(500); res.end('Server Error!'); return; } var headers = {'Content-type': mimeTypes[path.extname]}; res.writeHead(200, headers); res.end(data); }); return; } res.writeHead(404); res.end(); }); }).listen(8080);
在浏览器地址栏输入 http://localhost:8080/styles.css 或 http://localhost:8080/script.js 都会在网页上显示文件的内容。
在浏览器地址栏输入 http://localhost:8080/index.html 如图所示:
相关文章推荐
- Node.js开发手册(一)
- Node.js 入门手册:那些最流行的 Web 开发框架
- Node.js 入门手册:那些最流行的 Web 开发框架
- Node.js开发手册(四)-Redis数据库访问
- Node.js开发手册(四)-Redis数据库访问
- Node.js企业开发: 二应用开发
- Node.js开发入门(一)——安装Node.js及编辑器配置
- Node.js开发框架Express4.x
- Windows下Node.js开发入门(1)
- 零基础搭建Node.js、Express、Ejs、Mongodb服务器及应用开发入门
- Node.js v0.10.31API手册-事件
- KoaHub.JS基于Node.js开发的处理和显示日期代码
- 30天了解30种技术系列---(4)Node.js神级开发工具-WebStorm
- Vim配置Node.js开发工具
- 跟我学Nodejs(一)--- Node.js简介及安装开发环境
- 利用OpenShift托管Node.js Web服务进行微信公众号开发
- 20160109 Node.js 常用开发工具的使用
- 关于node.js的web框架的微信h5牌九平台开发及并发性能测试
- 在windows环境下基于sublime text3的node.js开发环境搭建
- 在Visual Studio上开发Node.js程序