如何在Nest.js中监听服务器文件夹变化并触发指定动作?
在Nest.js中实现文件夹文件新增监听
在Nest.js里监听文件夹的文件新增事件,主要有两种可靠方案:使用Node.js原生fs.watch,或者用更稳定的第三方库chokidar。以下是具体实现步骤:
方案一:使用Node.js原生fs模块
原生fs.watch不需要额外依赖,适合简单场景,但注意它在不同平台下的行为略有差异(比如Windows下可能触发多次事件)。
实现代码
创建一个监听服务,利用Nest的生命周期钩子初始化和销毁监听器:
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import * as fs from 'fs'; import { join } from 'path'; @Injectable() export class FileWatcherService implements OnModuleInit, OnModuleDestroy { private watcher: fs.FSWatcher; // 替换成你要监听的文件夹路径 private readonly targetDir = join(process.cwd(), 'watch-folder'); async onModuleInit() { // 确保目标文件夹存在,不存在则创建 if (!fs.existsSync(this.targetDir)) { fs.mkdirSync(this.targetDir, { recursive: true }); } // 启动文件夹监听 this.watcher = fs.watch(this.targetDir, (eventType, filename) => { // 仅处理文件新增(rename事件可能对应新增或删除,需要二次校验) if (eventType === 'rename' && filename) { const filePath = join(this.targetDir, filename); // 检查文件是否真实存在(排除删除场景) fs.access(filePath, fs.constants.F_OK, (err) => { if (!err) { this.handleNewFile(filePath); } }); } }); console.log(`已启动文件夹监听: ${this.targetDir}`); } // 处理新文件的业务逻辑 private handleNewFile(filePath: string) { console.log(`检测到新文件: ${filePath}`); // 这里添加你的自定义动作,比如: // - 读取文件内容 // - 存入数据库 // - 调用其他服务接口等 } // 模块销毁时关闭监听器,避免内存泄漏 async onModuleDestroy() { if (this.watcher) { this.watcher.close(); console.log('文件夹监听器已关闭'); } } }
方案二:使用chokidar库(推荐)
chokidar是专门用于文件系统监听的第三方库,解决了原生fs.watch的跨平台兼容性问题,还支持更多高级特性(比如等待文件写入完成、忽略初始文件等)。
步骤1:安装依赖
npm install chokidar # 或 yarn add chokidar
实现代码
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import * as chokidar from 'chokidar'; import { join } from 'path'; import * as fs from 'fs'; @Injectable() export class FileWatcherService implements OnModuleInit, OnModuleDestroy { private watcher: chokidar.FSWatcher; private readonly targetDir = join(process.cwd(), 'watch-folder'); async onModuleInit() { if (!fs.existsSync(this.targetDir)) { fs.mkdirSync(this.targetDir, { recursive: true }); } // 配置监听器选项 this.watcher = chokidar.watch(this.targetDir, { persistent: true, // 保持进程活跃 ignoreInitial: true, // 忽略初始化时已存在的文件 awaitWriteFinish: { stabilityThreshold: 2000, // 等待文件写入稳定2秒后再触发事件 pollInterval: 100 // 轮询间隔 } }); // 监听文件新增事件 this.watcher.on('add', (filePath) => { console.log(`检测到新文件: ${filePath}`); this.handleNewFile(filePath); }); // 可选:监听错误事件 this.watcher.on('error', (error) => { console.error('文件夹监听出错:', error); }); console.log(`已启动文件夹监听: ${this.targetDir}`); } private handleNewFile(filePath: string) { // 执行你的业务逻辑 } async onModuleDestroy() { if (this.watcher) { await this.watcher.close(); console.log('文件夹监听器已关闭'); } } }
注意事项
- 权限检查:确保Node.js进程对目标文件夹有读写权限
- 大文件处理:使用
awaitWriteFinish选项可以避免处理未完全写入的文件 - 内存泄漏:必须在
OnModuleDestroy钩子中关闭监听器 - 错误处理:建议添加错误事件监听,避免监听异常导致服务崩溃
内容的提问来源于stack exchange,提问作者mohamed souilmi
相关产品推荐
相关产品推荐

