【nodejs】简易的web在线文件浏览系统开发流程详解

在自家的路由器WiFi局域网内搭建一个web在线文件浏览系统,用nodejs搭建很简单,只需几步就完成了,方便随时浏览文件资源。

准备

  • 操作系统环境Windows或Linux
  • 需要安装nodejs

搭建web服务器

写一个server.js文件,代码如下

const http = require('http');
const url = require('url');
const util = require('util');
const fs = require('fs');

const port = '3000';
const PATH_DIV = '/';
const CurrentPath = __dirname.replace(/\\/g,PATH_DIV);

let app = http.createServer(function (req, res) {
	let response='Hello World';
	try{
		const reqURL = url.parse(req.url, true);
		// response = util.inspect(reqURL);
		// console.log(reqURL.search)
		
		let filename = decodeURIComponent(reqURL.pathname);
		let path = CurrentPath+filename;
		// console.log('path',path)
		
		let stat = fs.statSync(path);
		if (stat.isFile()){
			//返回或下载文件资源...
		}else{
			//返回当前目录列表...
		}
	}catch(e){
		console.error(e);
		response='Server has error';
		
		res.writeHead(404,{'Content-Type':'text/plain; charset:utf-8;'});
		res.end(response);
	}
})

app.listen(port, () => {
	//console.log('Web Server URL:', 'http://'+(getLocalIP() || 'localhost')+':'+port);
	console.log('Http Server running at path ', CurrentPath)
})

浏览目录功能

查询路径,返回网页展示列表,
以下是返回当前文件夹目录列表的代码

let list = fs.readdirSync(path);
let parentPath='';
if(filename!=PATH_DIV) {
    parentPath = filename.substring(0,filename.lastIndexOf(PATH_DIV));
    parentPath = `<li><a href="${parentPath.length>0?parentPath:PATH_DIV}">..</a></li>`;
}
if(!filename.endsWith(PATH_DIV)) filename+=PATH_DIV;
response = `<html><head><meta charset="utf-8"/></head><body><ol>`
    +`${parentPath}${list.map(item=>{
        let target = /\.[^\.]+$/.test(item)?'_blank':'_self';
        return `<li><a target="${target}" href="${filename+item}">${item}</a></li>`;
    })}</ol></body></html>`;
contentType='text/html';
res.writeHead(200,{'Content-Type':contentType+'; charset:utf-8;'});
res.end(response);

如有报错Error: EISDIR: illegal operation on a directory, read
说明是没有权限,
也可能是fs.readFileSync()读取的不是文件,或路径不对引起的

浏览文件功能

以下是实现返回或下载文件资源的代码

let extname = filename.substring(filename.lastIndexOf('.')+1);
let contentType;
switch(extname){
	case 'html':
	case 'htm':
		contentType='text/html';
		break;
	case 'css':
		contentType='text/css';
		break;
	case 'js':
		contentType='application/x-javascript';
		break;
	case 'txt':
		contentType='text/plain';
		break;
	default:
}
if(contentType){
	res.writeHead(200,{'Content-Type':contentType+'; charset:utf-8;'});
	response=fs.readFileSync(path);
	res.end(response);
}
else{
	// let file = fs.readFileSync(filename);
	// console.log('response',filename);
	// 直接访问文件
	// res.redirect(filename);
	// return;
	// 二进制文件
	res.setHeader('Content-Type', 'application/octet-stream');
	//Invalid character in header content ["Content-Disposition"]  filename需要编码,否则报这个错误
	// 直接下载
	// res.setHeader('Content-Disposition','attachment;filename='+encodeURIComponent(event.name));
	// 直接查看
	res.setHeader("Content-Disposition","inline;filename=" + encodeURIComponent(filename.substring(1)));
	res.setHeader('Content-Length',stat.size);
	fs.createReadStream(path).pipe(res);
}

执行node命令

在当前的目录下,打开终端,(Windows的是CMD),输入命令node server.js

如果运行不报错的话,就会输出Http Server running at...
然后,打开浏览器访问http://127.0.0.1:8080

部分浏览器自带支持打开部分文件,
若浏览器不支持,换个浏览器试试

如觉得网页展示文件夹目录不好看,自己改网页布局样式就好了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TA远方

谢谢!收到你的爱╮(╯▽╰)╭

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值