https://www.cnblogs.com/bruce-gou/p/6082132.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>node读取所有图片设置背景图</title>
    8. <style>
    9. html,
    10. body {
    11. height: 100%
    12. }
    13. body {
    14. margin: 0;
    15. background: url('./blue-bg.png') no-repeat center;
    16. background-size: cover;
    17. }
    18. </style>
    19. </head>
    20. <body>
    21. </body>
    22. <script>
    23. var fs = require("fs");
    24. // 引用imageinfo模块
    25. var image = require("imageinfo");
    26. function readFileList(path, filesList) {
    27. var files = fs.readdirSync(path);
    28. files.forEach(function (itm, index) {
    29. var stat = fs.statSync(path + itm);
    30. if (stat.isDirectory()) {
    31. //递归读取文件
    32. readFileList(path + itm + "/", filesList)
    33. } else {
    34. var obj = {};//定义一个对象存放文件的路径和名字
    35. obj.path = path;//路径
    36. obj.filename = itm//名字
    37. filesList.push(obj);
    38. }
    39. })
    40. }
    41. // 自己改进的
    42. function readSubFileList(path, filesList) {
    43. var files = fs.readdirSync(path);
    44. files.forEach(function (itm, index) {
    45. var stat = fs.statSync(path + itm);
    46. if (stat.isDirectory()) {
    47. //递归读取文件
    48. var obj = {};
    49. obj.path = itm;
    50. obj.filename = [];
    51. filesList.push(obj);
    52. readSubFileList(path + itm + "/", obj.filename)
    53. } else {
    54. // 不是文件夹就存进obj.filename | filesList
    55. filesList.push(itm) //名字
    56. }
    57. })
    58. }
    59. var getFiles = {
    60. //获取文件夹下的所有文件
    61. getFileList: function (path) {
    62. var filesList = [];
    63. readFileList(path, filesList);
    64. return filesList;
    65. },
    66. getSubFileList: function (path) {
    67. var filesList = [];
    68. readSubFileList(path, filesList);
    69. return filesList;
    70. },
    71. //获取文件夹下的所有图片
    72. getImageFiles: function (path) {
    73. var imageList = [];
    74. this.getFileList(path).forEach((item) => {
    75. var ms = image(fs.readFileSync(item.path + item.filename));
    76. ms.mimeType && (imageList.push(item.filename))
    77. });
    78. return imageList;
    79. },
    80. //获取文件夹下所有非图片的文件 2018年8月18日 19:15:13更新
    81. getTxtList: function (path) {
    82. return this.getFileList(path).filter((item) => {
    83. var ms = image(fs.readFileSync(item.path + item.filename));
    84. return !ms.mimeType
    85. });
    86. }
    87. }
    88. </script>
    89. </html>

    blue-bg.7z