electron基础教程——文件操作(2-多文件)
单文件操作看这里
看到这里就当您看过文件操作(一)了噢,如果真的没看,送一张飞机票免费过去
实现过程和文件操作(一)是一样的,下面只展示不一样的地方
- 选取文件
// 选择多文件
const choseMoreFile = async () => {
// 选择要读取的文件
dialog.showOpenDialog({ properties: ["multiSelections"] }).then((res) => {
// 多文件读取
res.filePaths.length > 1 &&
res.filePaths.map((val) => {
readMoreFileContent(val).then((fileText) => {
console.log(fileText);
fileMoreContent.value.push(fileText);
});
});
});
};
注:该方法比单文件选择多了一个properties:[“multiSelections”],这个属性是打开窗口可以选择多个文件
- 读取文件内容
// 读取多文件内容
const readMoreFileContent = (filePath) => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, { encoding: "utf-8" }, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
注:这里用promise的目的是让文件有顺序的读取,不至于错乱
总结:多文件需要注意的是dialog添加properties:[“multiSelections”]该属性以确保能选多个文件,另读取文件改用promise的方式,主要是避免读取顺序不正确。个人见解,如有错误或者更好的方法还请不吝赐教😀😀😀