在自家的路由器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
部分浏览器自带支持打开部分文件,
若浏览器不支持,换个浏览器试试
如觉得网页展示文件夹目录不好看,自己改网页布局样式就好了