我们可以将本地文件上传到沙箱内。

上传单个文件

import fs from 'fs'
import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

// 从本地文件系统读取文件内容
const content = fs.readFileSync('/local/path')
// 将文件上传到沙箱
await sandbox.files.write('/path/in/sandbox', content)

上传目录/多个文件

import fs from 'fs'
import path from 'path'
import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

// 读取目录中的所有文件,并将它们的路径和内容存储在一个数组中
const readDirectoryFiles = (directoryPath) => {
  // 读取本地目录中的所有文件
  const files = fs.readdirSync(directoryPath);

  // 将文件映射为具有路径和数据的对象
  const filesArray = files
    .filter(file => {
      const fullPath = path.join(directoryPath, file);
      // 如果是一个目录,则跳过
      return fs.statSync(fullPath).isFile();
    })
    .map(file => {
      const filePath = path.join(directoryPath, file);
    
      // 读取每个文件的内容
      return {
        path: filePath,
        data: fs.readFileSync(filePath, 'utf8')
      };
    });

  return filesArray;
};

// 使用示例
const files = readDirectoryFiles('/local/dir');
console.log(files); 
// 输出示例:
// [
//   { path: '/local/dir/file1.txt', data: 'File 1 contents...' },
//   { path: '/local/dir/file2.txt', data: 'File 2 contents...' },
//   ...
// ]

await sandbox.files.write(files)