Copy
import { Sandbox, FilesystemEventType } from 'ppio-sandbox/code-interpreter'
const sandbox = await Sandbox.create()
const dirname = '/tmp'
// 开始监视目录的变化
const handle = await sandbox.files.watchDir(dirname, async (event) => {
console.log(`got event: ${event.type} - ${event.name}`)
if (event.type === FilesystemEventType.WRITE) {
console.log(`wrote to file ${event.name}`)
}
})
// 触发文件写入事件
await sandbox.files.write(`${dirname}/test-file`, 'test-file-content')
// 停止监视
handle.stop()
await sandbox.kill()
递归监视
如果需要监视到目录下子文件夹(包括多级嵌套的文件夹)内容的变化,您可以使用recursive
参数启用 “递归监视”。
当快速创建新文件夹时(例如多级的文件夹路径),除了
CREATE
之外的事件可能不会被触发。为了避免这种行为,请提前创建所需的文件夹结构。Copy
import { Sandbox, FilesystemEventType } from 'ppio-sandbox/code-interpreter'
const sandbox = await Sandbox.create()
const dirname = '/tmp'
// 开始监视目录的变化
const handle = await sandbox.files.watchDir(dirname, async (event) => {
console.log(`got event: ${event.type} - ${event.name}`)
if (event.type === FilesystemEventType.WRITE) {
console.log(`wrote to file ${event.name}`)
}
}, {
recursive: true
})
// 触发文件写入事件
await sandbox.files.write(`${dirname}/test-folder/test-file`, 'test-file-content')
// 停止监视
handle.stop()
await sandbox.kill()