上传单个文件
Copy
import fs from 'fs'
import { Sandbox } from 'ppio-sandbox/code-interpreter'
const sandbox = await Sandbox.create()
// 从本地文件系统读取文件内容
const localFilePath = '../local-test-file'
const content = fs.readFileSync(localFilePath, 'utf8')
// 将文件上传到沙箱
const filePathInSandbox = '/tmp/test-file'
const result = await sandbox.files.write(filePathInSandbox, content)
console.log(result)
await sandbox.kill()
上传目录/多个文件
Copy
import fs from 'fs'
import path from 'path'
import { Sandbox } from 'ppio-sandbox/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 localDirectoryPath = '../local-test-dir'
const files = readDirectoryFiles(localDirectoryPath);
console.log(files);
// 输出示例:
// [
// {
// path: '../local-test-dir/local-test-file-1',
// data: 'test-file-content'
// },
// {
// path: '../local-test-dir/local-test-file-2',
// data: 'test-file-content'
// }
// ]
// 指定上传到沙箱里的文件路径
files.forEach(file => {
file.path = file.path.replace('../local-test-dir', '/tmp')
})
const result = await sandbox.files.write(files)
console.log(result)
// 输出示例:
// [
// {
// name: 'local-test-file-1',
// path: '/tmp/local-test-file-1',
// type: 'file'
// },
// {
// name: 'local-test-file-2',
// path: '/tmp/local-test-file-2',
// type: 'file'
// }
// ]
await sandbox.kill()