You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取根目录images/source下所有图片并拼接相对路径存入数组

实现方案

你可以对readdirSync返回的文件名数组做遍历拼接,参考实现代码如下:

const fs = require('fs');
const path = require('path');

// 定义目标文件夹的相对路径(相对于项目根目录)
const basePath = 'images/source';
// 读取目录下所有文件名并排序
const fileNames = fs.readdirSync(path.join(__dirname, basePath)).sort();
// 拼接得到完整相对路径数组
const images = fileNames.map(fileName => path.join(basePath, fileName));

这里使用path.join拼接路径可以自动适配不同操作系统的路径分隔符,避免手动拼接/出现的兼容性问题。

如果需要过滤掉目录中非图片格式的文件,可以增加过滤逻辑:

const fs = require('fs');
const path = require('path');

const basePath = 'images/source';
// 允许的图片后缀列表
const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
const fileNames = fs.readdirSync(path.join(__dirname, basePath)).sort();

const images = fileNames
  // 过滤符合后缀要求的文件,同时转为小写避免大小写后缀漏匹配
  .filter(fileName => allowedExts.includes(path.extname(fileName).toLowerCase()))
  .map(fileName => path.join(basePath, fileName));

内容的提问来源于stack exchange,提问作者ShankarGuru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 13:24:02