function deepFindFile(){ let imgArrayInfo = [] // 创建输出根目录 if(!fs.existsSync(this.outputPath)) fs.mkdirSync(this.outputPath) fs.readdirSync(this.inputPath).forEach(file=>{ let filePath = path.resolve(this.inputPath,file) let targetPath = path.resolve(this.outputPath,file) let fileStat = fs.statSync(filePath) if(fileStat.isDirectory()){ // 创建对应输出目录 if(!fs.existsSync(targetPath)) fs.mkdirSync(targetPath) imgArrayInfo = [...imgArrayInfo,...this.deepFindFile()] }else{ const fileNameReg = /\.(jpe?g|png|svg|gif)$/ if(fileNameReg.test(filePath)){ let imgData = fs.readFileSync(filePath) imgArrayInfo.push({ inputPath:filePath, //图片文件 原路径 file:imgData, //图片文件 目标存放路径 targetPath }) } } }) return imgArrayInfo } 为什么这个函数会死循环
时间: 2024-02-14 19:18:46 浏览: 21
这个函数会死循环是因为在处理子目录时,它没有对子目录进行递归调用该函数,导致程序一直在同一个目录下寻找文件,无法跳出循环。需要在处理子目录时,加上递归调用该函数,比如在 if (fileStat.isDirectory()) 分支中加上 `imgArrayInfo = [...imgArrayInfo, ...this.deepFindFile.call({inputPath: filePath, outputPath: targetPath})]` 就可以了。
相关问题
fs.existsSync is not a function
这个错误通常出现在 Node.js 中,它提示说 `fs.existsSync` 不是一个函数。这可能是因为你的代码中没有正确引入 `fs` 模块。
你需要在代码中添加以下代码来引入 `fs` 模块:
```javascript
const fs = require('fs');
```
然后,你可以使用 `fs.existsSync` 函数来检查指定的文件是否存在。例如:
```javascript
const filePath = '/path/to/file.txt';
if (fs.existsSync(filePath)) {
console.log('File exists');
} else {
console.log('File does not exist');
}
```
在上面的示例中,如果 `/path/to/file.txt` 存在,则会输出 `File exists`,否则会输出 `File does not exist`。
在electron的渲染进程中导包会发生TypeError: fs.existsSync is not a function
在 Electron 的渲染进程中,由于 Node.js 环境与浏览器环境的差异,无法直接使用 Node.js 的模块,例如 fs 模块。
要在渲染进程中使用 Node.js 的模块,可以使用 Electron 提供的 remote 模块,通过在主进程中执行相关操作并将结果传递给渲染进程。
示例代码如下:
在主进程中,创建一个获取文件是否存在的函数:
```javascript
const fs = require('fs');
function fileExists(path) {
return fs.existsSync(path);
}
module.exports = fileExists;
```
在渲染进程中,通过 remote 模块调用主进程中的函数:
```javascript
const { remote } = require('electron');
const fileExists = remote.require('./fileExists');
if (fileExists('path/to/file')) {
// 文件存在
} else {
// 文件不存在
}
```
这样就可以在 Electron 的渲染进程中使用 Node.js 的模块了。