XStack

Deep into details

0%

使用Node.js监听macOS的u盘插入拔出

代码#

1
2
3
4
5
6
7
8
9
10
11
const fs = require('fs');
var path = '/Volumes/';
fs.watch(path, function (event, filename) {
fs.exists(path+filename, function(exist){
if(exist){
console.log("mount as:"+filename);
}else{
console.log("unmount:"+filename);
}
});
});

原理#

系统会mount设备到/Volumes/目录,创建一个新文件夹,所以,监听/Volumes/目录变动即可