您的位置:首页 > Web前端 > Node.js

菜鸟小白使用node.js搭建简单服务器(可请求图片,html,js,css,json等文件)

2018-04-07 16:45 1251 查看

使用node.js搭建简单服务器

前言:以下步骤在安装好node的环境前提下进行,未安装者请先安装好node,再尝试

注:如若以下代码存在错误,欢迎读者指出

搭建步骤如下:

一、创建server.js(主要用于搭建服务器的文件)

const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
var mime = require('./mime'); // 加载我们的mime.js
var config = require('./config');

const server =  http.createServer(function(req,res){
var pathName = url.parse(req.url).pathname;  // 获取文件名"/xxx"
// 对中文进行解码,防止乱码
pathName = decodeURI(pathName);
// 获取资源的绝对路径
var realFilePath = path.resolve(__dirname+ pathName);
console.log(realFilePath);
// 获取对应文件的文档类型
var ext = path.extname(pathName); // 获取后缀名,如'.html'
ext = ext?ext.slice(1): 'notKnow';  // 取掉.符号

//通过和mine.js里面设定好的正则进行匹配,判断当前请求的图片是否为图片
if (ext.match(config.Expires.fileMatch)) {
var expires = new Date();
expires.setTime(expires.getTime() + config.Expires.maxAge * 1000);
// 设置响应头
res.setHeader("Expires", expires.toUTCString());
res.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge);
}
// 定义未知文档的类型MIME
var contentType = mime[ext] || "text/plain"; // 后缀名存在就进行映射,不存在就是'text/plain'

//从文件系统中都去请求的文件内容
fs.readFile(pathName.substr(1),function(err, data) {
if(err) {
console.log(err);
//HTTP 状态码 404 : NOT FOUND
//Content Type:text/plain
res.writeHead(404,{'Content-Type': contentType});
}
else {
//HTTP 状态码 200 : OK
//Content Type:text/plain
res.writeHead(200,{'Content-Type': contentType});
var content =  fs.readFileSync(realFilePath,"binary");   //解释图片时,格式必须为 binary 否则会出错
//写会相应内容
res.write(content,"binary"); //解释图片时,格式必须为 binary,否则会出错

}
//发送响应数据
res.end();
});
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');


二、相关require文件

1、config.js代码如下:

exports.Expires = {
fileMatch: /^(jpeg|gif|png|jpg)$/ig, // 这只是个实例
maxAge: 60 * 60 * 24 * 365
};


2、mime.js(保存用到的mime类型)代码如下:

module.exports = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};


三、运行

(1)通过cmd命令跳转到对应的项目文件目录下,执行命令node server.js

(2) 在浏览器进行访问,在url栏中输入http://127.0.0.1:8081/index.html(文件夹下要有index.html文件)

参考: 如何使用nodejs创建Web服务器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node web服务器 前端