文件系统
监视目录变化
本节演示如何监视目录下文件的变化。
Copy
Ask AI
import { Sandbox, FilesystemEventType } from '@e2b/code-interpreter'
const sandbox = await Sandbox.create()
const dirname = '/home/user'
// 开始监视目录的变化
const handle = await sandbox.files.watchDir(dirname, async (event) => {
console.log(event)
if (event.type === FilesystemEventType.WRITE) {
console.log(`wrote to file ${event.name}`)
}
})
// 触发文件写入事件
await sandbox.files.write(`${dirname}/my-file`, 'hello')
递归监视
如果需要监视到目录下子文件夹(包括多级嵌套的文件夹)内容的变化,您可以使用 recursive
参数启用 “递归监视”。
当快速创建新文件夹时(例如多级的文件夹路径),除了 CREATE
之外的事件可能不会被触发。为了避免这种行为,请提前创建所需的文件夹结构。
Copy
Ask AI
import { Sandbox, FilesystemEventType } from '@e2b/code-interpreter'
const sandbox = await Sandbox.create()
const dirname = '/home/user'
// 开始监视目录的变化
const handle = await sandbox.files.watchDir(dirname, async (event) => {
console.log(event)
if (event.type === FilesystemEventType.WRITE) {
console.log(`wrote to file ${event.name}`)
}
}, {
recursive: true
})
// 触发文件写入事件
await sandbox.files.write(`${dirname}/my-folder/my-file`, 'hello')
在此页面
助手
Responses are generated using AI and may contain mistakes.