https://www.cnblogs.com/bruce-gou/p/6082132.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>node读取所有图片设置背景图</title>
<style>
html,
body {
height: 100%
}
body {
margin: 0;
background: url('./blue-bg.png') no-repeat center;
background-size: cover;
}
</style>
</head>
<body>
</body>
<script>
var fs = require("fs");
// 引用imageinfo模块
var image = require("imageinfo");
function readFileList(path, filesList) {
var files = fs.readdirSync(path);
files.forEach(function (itm, index) {
var stat = fs.statSync(path + itm);
if (stat.isDirectory()) {
//递归读取文件
readFileList(path + itm + "/", filesList)
} else {
var obj = {};//定义一个对象存放文件的路径和名字
obj.path = path;//路径
obj.filename = itm//名字
filesList.push(obj);
}
})
}
// 自己改进的
function readSubFileList(path, filesList) {
var files = fs.readdirSync(path);
files.forEach(function (itm, index) {
var stat = fs.statSync(path + itm);
if (stat.isDirectory()) {
//递归读取文件
var obj = {};
obj.path = itm;
obj.filename = [];
filesList.push(obj);
readSubFileList(path + itm + "/", obj.filename)
} else {
// 不是文件夹就存进obj.filename | filesList
filesList.push(itm) //名字
}
})
}
var getFiles = {
//获取文件夹下的所有文件
getFileList: function (path) {
var filesList = [];
readFileList(path, filesList);
return filesList;
},
getSubFileList: function (path) {
var filesList = [];
readSubFileList(path, filesList);
return filesList;
},
//获取文件夹下的所有图片
getImageFiles: function (path) {
var imageList = [];
this.getFileList(path).forEach((item) => {
var ms = image(fs.readFileSync(item.path + item.filename));
ms.mimeType && (imageList.push(item.filename))
});
return imageList;
},
//获取文件夹下所有非图片的文件 2018年8月18日 19:15:13更新
getTxtList: function (path) {
return this.getFileList(path).filter((item) => {
var ms = image(fs.readFileSync(item.path + item.filename));
return !ms.mimeType
});
}
}
</script>
</html>