新建一个 node 文件夹, 创建 service.js 文件, 新建一个 "file" 文件夹, 将你的访问的静态资源放在 file 里.
在 node 文件下运行 node server2.js
即可在 http://localhost:8001/+ 资源名, 访问你的资源
- var http = require('http');
- var fs = require('fs');// 引入文件读取模块
- var documentRoot = '/Users/treeFighting/node/file';
- // 需要访问的文件的存放目录
- var server= http.createServer(function(req,res){
- var url = req.url;
- // 客户端输入的 url, 例如如果输入 localhost:8888/index.html
- // 那么这里的 url == /index.html
- var file = documentRoot + url;
- console.log(url);
- //E:/PhpProject/html5/websocket/www/index.html
- fs.readFile( file , function(err,data){
- /*
- 一参为文件路径
- 二参为回调函数
- 回调函数的一参为读取错误返回的信息, 返回空就没有错误
- 二参为读取成功返回的文本内容
- */
- if(err){
- res.writeHeader(404,{
- 'content-type' : 'text/html;charset="utf-8"'
- });
- res.write('<h1>404 错误 </h1><p > 你要找的页面不存在 </p>');
- res.end();
- }else{
- res.writeHeader(200,{
- 'content-type' : 'text/html;charset="utf-8"'
- });
- res.write(data);// 将 index.html 显示在客户端
- res.end();
- }
- });
- }).listen(8001);
- console.log('请访问 localhost:8001/');
来源: http://www.qdfuns.com/article/35185/f82ca027be0f66b5c7722a9bb55afd4a.html