博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
node搭建服务器
阅读量:4673 次
发布时间:2019-06-09

本文共 1973 字,大约阅读时间需要 6 分钟。

创建简单的服务器,可以简单连接

var http = require("http");var server = http.createServer();server.on("request",function(req,res){    res.end("ok");})server.listen(3000);console.log("running in 3000");

 判断是文件夹还是文件

fs.stat("./08.html",function(err,stats){        if(stats.isDirectory()){            console.log("是文件夹");        }else if(stats.isFile()){            console.log("是文件");        }    })

判断文件

fs.access("./08.html",function(err){        if(err){            console.log("文件不存在");            throw err;        }        fs.readFile("./08.html",function(err,data){            if(err){                throw err;            }            console.log("文件存在");            res.end(data);        })    })

MIME支持

现在给客户端返回文件时,我们并没有指定Content-Type头,虽然你可能发现访问文本或图片浏览器都可以正确显示出文字或图片,但这并不符合规范。任何包含实体主体(entity body)的响应都应在头部指明文件类型,否则浏览器无从得知类型时,就会自行猜测(从文件内容以及url中寻找可能的扩展名)。响应如指定了错误的类型也会导致内容的错乱显示,如明明返回的是一张jpeg图片,却错误指定了header:'Content-Type': 'text/html',会收到一堆乱码。

var mime = {    'psd': 'application/x-photoshop',    'ppt': 'application/powerpoint',    'php': 'application/x-httpd-php',    'mp3': 'audio/mp3',    'jpg': 'image/jpeg',    'png': 'image/png',    'tiff': 'image/tiff',    'tif': 'image/tiff',    'css': 'text/css',    'html': 'text/html',    'htm': 'text/html',    'txt': 'text/plain',    'text': 'text/plain',    'qt': 'video/quicktime',    'mov': 'video/quicktime',    'avi': 'video/x-msvideo',    'movie': 'video/x-sgi-movie',    'doc': 'application/msword',    'word': 'application/msword',    'json': 'text/json'}

 服务器获取请求后可以对请求路径做出处理的几种方法

var path = require("path"); console.log(path.basename("/foo/bar/index.html"));//"index.html" console.log(path.basename("/foo/bar/index"));//"index" console.log(path.extname("/foo/bar/index.html"));//".html" console.log(path.extname("/foo/bar/index.css"));//".css" console.log(path.extname("/foo/bar/index"));//"" console.log(path.dirname('/foo/bar/baz/asdf/quux')); // 返回: '/foo/bar/baz/asdf'

 

转载于:https://www.cnblogs.com/tangdiying/p/10476715.html

你可能感兴趣的文章