|
1 | | -# Run JavaScript code |
2 | | -Use the `runCode`/`run_code` method to run JavaScript code inside the sandbox. |
3 | | -You'll need to pass the `language` parameter with value `javascript` or `js`. |
| 1 | +# Run JavaScript and TypeScript code |
| 2 | + |
| 3 | +Use the `runCode`/`run_code` method to run JavaScript and TypeScript code inside the sandbox. |
| 4 | +You'll need to pass the `language` parameter with value `javascript` or `js` for JavaScript and `typescript` or `ts` for TypeScript. |
| 5 | + |
| 6 | +<Note> |
| 7 | +The E2B Code Interpreter supports TypeScript, top-level await, ESM-style imports and automatic promises resolution. |
| 8 | +</Note> |
| 9 | + |
4 | 10 | <CodeGroup> |
5 | 11 | ```js |
6 | | -import { Sandbox } from '@e2b/code-interpreter' |
| 12 | +import { Sandbox } from "@e2b/code-interpreter"; |
| 13 | + |
| 14 | +// Create a new sandbox |
| 15 | +const sbx = await Sandbox.create(); |
| 16 | + |
| 17 | +// Install the axios package |
| 18 | +await sbx.commands.run("npm install axios"); |
| 19 | + |
| 20 | +// Run the code |
| 21 | +const execution = await sbx.runCode(` |
| 22 | + import axios from "axios"; |
| 23 | +
|
| 24 | + const url: string = "https://api.github.com/status"; |
| 25 | + const response = await axios.get(url); |
| 26 | + response.data; |
| 27 | +`, |
| 28 | + { language: "ts" } |
| 29 | +); |
7 | 30 |
|
8 | | -const sbx = await Sandbox.create() |
9 | | -const execution = await sbx.runCode('console.log("Hello, world!")', { language: 'js' }) |
10 | | -console.log(execution) |
| 31 | +console.log(execution); |
| 32 | + |
| 33 | +// Execution { |
| 34 | +// results: [], |
| 35 | +// logs: { |
| 36 | +// stdout: [ "{ message: 'GitHub lives! (2025-05-28 10:49:55 -0700) (1)' }\n" ], |
| 37 | +// stderr: [], |
| 38 | +// }, |
| 39 | +// error: undefined, |
| 40 | +// executionCount: 1, |
| 41 | +// text: [Getter], |
| 42 | +// toJSON: [Function: toJSON], |
| 43 | +// } |
11 | 44 | ``` |
12 | 45 | ```python |
13 | 46 | from e2b_code_interpreter import Sandbox |
14 | 47 |
|
| 48 | +# Create a new sandbox |
15 | 49 | sbx = Sandbox() |
16 | | -execution = sbx.run_code('console.log("Hello, world!")', language="js") |
| 50 | + |
| 51 | +# Install the axios package |
| 52 | +sbx.commands.run("npm install axios") |
| 53 | + |
| 54 | +# Run the code |
| 55 | +execution = sbx.run_code(""" |
| 56 | + import axios from "axios"; |
| 57 | +
|
| 58 | + const url: string = "https://api.github.com/status"; |
| 59 | + const response = await axios.get(url); |
| 60 | + response.data; |
| 61 | +""", |
| 62 | + language="ts", |
| 63 | +) |
| 64 | + |
17 | 65 | print(execution) |
| 66 | + |
| 67 | +# Execution( |
| 68 | +# Results: [ |
| 69 | +# Result({ message: 'GitHub lives! (2025-05-28 10:48:47 -0700) (1)' }) |
| 70 | +# ], |
| 71 | +# Logs: Logs(stdout: [], stderr: []), |
| 72 | +# Error: None |
| 73 | +# ) |
18 | 74 | ``` |
19 | 75 | </CodeGroup> |
0 commit comments