Node.js 文件杀毒(ClamAV)
通过 Node.js 调用 ClamAV 杀毒引擎,对上传文件进行病毒扫描。
依赖
bash
npm install clamscan基础用法
js
import NodeClam from 'clamscan'
const clamscan = await new NodeClam().init({
removeInfected: false, // 不自动删除感染文件
quarantineInfected: false,// 不隔离
scanLog: '/var/log/clamav.log',
debugMode: false,
})
// 扫描单个文件
const { isInfected, viruses } = await clamscan.scanFile('/path/to/file.exe')
if (isInfected) {
console.log('病毒:', viruses)
} else {
console.log('安全')
}
// 扫描目录
const result = await clamscan.scanDir('/uploads')集成到文件上传流程
js
app.post('/upload', upload.single('file'), async (req, res) => {
const filePath = req.file.path
const { isInfected, viruses } = await clamscan.scanFile(filePath)
if (isInfected) {
fs.unlinkSync(filePath)
return res.status(400).send(`文件包含病毒: ${viruses.join(', ')}`)
}
res.send('上传成功')
})前提条件
需要先安装 ClamAV 引擎:
- Linux:
sudo apt install clamav clamav-daemon - macOS:
brew install clamav - Windows: 安装 ClamAV for Windows