node文件服务器,nodejs一个简单的文件服务器的创建方法

简单的文件服务器

有时候,我们想读取一些服务器上的文件,但是又不想写太复杂的程序,可以考虑用nodejs,可以很简单的写出一个文件服务器

下面是我写的一个简单的文件服务器,附带缓存功能,这是github链接,或者直接复制下面的代码运行即可,需要安装mime的依赖

const port = 3004; // 端口号

const http = require('http');

const url = require('url');

const fs = require('fs');

const path = require('path');

const mime = require('mime');

const STATIC_FOLDER = 'public'; // 默认读取public文件夹下的文件

const IS_OPEN_CACHE = true; // 是否开启缓存功能

const CACHE_TIME = 10;// 告诉浏览器多少时间内可以不用请求服务器,单位:秒

const server = http.createServer((req, res) => {

const obj = url.parse(req.url); // 解析请求的url

let pathname = obj.pathname; // 请求的路径

if (pathname === '/') {

pathname = './index.html';

}

const realPath = path.join(__dirname, STATIC_FOLDER, pathname); // 获取物理路径

// 获取文件基本信息,包括大小,创建时间修改时间等信息

fs.stat(realPath, (err, stats) => {

let endFilePath = '', contentType = '';

if (err || stats.isDirectory()) {

// 报错了或者请求的路径是文件夹,则返回404

res.writeHead(404, 'not found', {

'Content-Type': 'text/plain'

});

res.write(`the request ${pathname} is not found`);

res.end();

} else {

let ext = path.extname(realPath).slice(1); // 获取文件拓展名

contentType = mime.getType(ext) || 'text/plain';

endFilePath = realPath;

if (!IS_OPEN_CACHE) {

// 未开启缓存

let raw = fs.createReadStream(endFilePath);

res.writeHead(200, 'ok');

raw.pipe(res);

} else {

// 获取文件最后修改时间,并把时间转换成世界时间字符串

let lastModified = stats.mtime.toUTCString();

const ifModifiedSince = 'if-modified-since';

// 告诉浏览器在规定的什么时间内可以不用请求服务器,直接使用浏览器缓存,不过貌似没有生效,需要再学习一下为什么

let expires = new Date();

expires.setTime(expires.getTime() + CACHE_TIME * 1000);

res.setHeader("Expires", expires.toUTCString());

res.setHeader('Cache-Control', 'max-age=' + CACHE_TIME);

if (req.headers[ifModifiedSince] && lastModified === req.headers[ifModifiedSince]) {

// 请求头里包含请求ifModifiedSince且文件没有修改,则返回304

res.writeHead(304, 'Not Modified');

res.end();

} else {

// 返回头Last-Modified为当前请求文件的最后修改时间

res.setHeader('Last-Modified', lastModified);

// 返回文件

let raw = fs.createReadStream(endFilePath);

res.writeHead(200, 'ok');

raw.pipe(res);

}

}

}

});

});

server.listen(port);

console.log(`server is running at http://localhost:${port}`)

不过目前还有一点问题,服务器缓存返回304,还有修改文件后,再次请求会返回最新文件这个功能目前没有问题,不过设置的Cache-Control和Expires后,在规定的时间内还是会请求服务器,这个还需要再看一下怎么回事,要是有人了解的话可以告诉我一下,谢谢。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值