0
# JavaScript Execution
1
2
Core functionality for evaluating and executing JavaScript code from Python applications.
3
4
## Overview
5
6
PyExecJS provides three main execution modes: evaluation (returning results), execution (returning output), and compilation (creating reusable contexts). All functions automatically select the best available JavaScript runtime unless specifically configured.
7
8
## Core Functions
9
10
### eval()
11
12
Evaluate JavaScript expressions and return the computed result.
13
14
```python { .api }
15
def eval(source, cwd=None):
16
"""
17
Evaluate JavaScript source code and return the result.
18
19
Args:
20
source (str): JavaScript source code to evaluate
21
cwd (str, optional): Working directory for execution
22
23
Returns:
24
any: Result of JavaScript evaluation (int, float, str, bool, list, dict, or None)
25
26
Raises:
27
ProgramError: When JavaScript code contains syntax or runtime errors
28
RuntimeError: When JavaScript runtime engine encounters errors
29
RuntimeUnavailableError: When no JavaScript runtime is available
30
"""
31
```
32
33
### exec_()
34
35
Execute JavaScript code and return the standard output.
36
37
```python { .api }
38
def exec_(source, cwd=None):
39
"""
40
Execute JavaScript source code and return stdout output.
41
42
Args:
43
source (str): JavaScript source code to execute
44
cwd (str, optional): Working directory for execution
45
46
Returns:
47
str: Standard output from JavaScript execution
48
49
Raises:
50
ProgramError: When JavaScript code contains syntax or runtime errors
51
RuntimeError: When JavaScript runtime engine encounters errors
52
RuntimeUnavailableError: When no JavaScript runtime is available
53
"""
54
```
55
56
### compile()
57
58
Compile JavaScript source code into a reusable execution context.
59
60
```python { .api }
61
def compile(source, cwd=None):
62
"""
63
Compile JavaScript source into a reusable context object.
64
65
Args:
66
source (str): JavaScript source code to compile
67
cwd (str, optional): Working directory for compilation
68
69
Returns:
70
Context object: Compiled JavaScript execution context with eval(), exec_(), and call() methods
71
72
Raises:
73
ProgramError: When JavaScript code contains syntax errors
74
RuntimeError: When JavaScript runtime engine encounters errors
75
RuntimeUnavailableError: When no JavaScript runtime is available
76
"""
77
```
78
79
## Usage Examples
80
81
### Basic Evaluation
82
83
```python
84
import execjs
85
86
# Simple expressions
87
result = execjs.eval("2 + 3 * 4") # 14
88
name = execjs.eval("'Hello'.toUpperCase()") # "HELLO"
89
90
# Complex objects
91
data = execjs.eval("({name: 'John', age: 30, scores: [85, 92, 78]})")
92
# Returns: {'name': 'John', 'age': 30, 'scores': [85, 92, 78]}
93
```
94
95
### Execution with Output
96
97
```python
98
import execjs
99
100
# Console output
101
output = execjs.exec_("console.log('Processing...'); console.log('Done!')")
102
# Returns: "Processing...\nDone!\n"
103
104
# Multiple statements
105
code = """
106
for (var i = 1; i <= 3; i++) {
107
console.log('Step ' + i);
108
}
109
"""
110
output = execjs.exec_(code)
111
# Returns: "Step 1\nStep 2\nStep 3\n"
112
```
113
114
### Compilation and Reuse
115
116
```python
117
import execjs
118
119
# Compile JavaScript with functions
120
js_code = """
121
var math = {
122
add: function(a, b) { return a + b; },
123
multiply: function(a, b) { return a * b; },
124
factorial: function(n) {
125
if (n <= 1) return 1;
126
return n * this.factorial(n - 1);
127
}
128
};
129
"""
130
131
ctx = execjs.compile(js_code)
132
133
# Use compiled context multiple times
134
result1 = ctx.call("math.add", 5, 3) # 8
135
result2 = ctx.call("math.multiply", 4, 7) # 28
136
result3 = ctx.call("math.factorial", 5) # 120
137
```
138
139
## Working Directory Support
140
141
All execution functions support specifying a working directory for JavaScript execution:
142
143
```python
144
import execjs
145
import os
146
147
# Execute in specific directory
148
result = execjs.eval("typeof require !== 'undefined'", cwd="/path/to/node/project")
149
150
# Useful for Node.js modules that depend on relative paths
151
ctx = execjs.compile("var fs = require('fs');", cwd="/home/user/project")
152
```
153
154
## Type Conversion
155
156
PyExecJS automatically converts between JavaScript and Python types:
157
158
| JavaScript Type | Python Type |
159
|----------------|-------------|
160
| `number` | `int` or `float` |
161
| `string` | `str` |
162
| `boolean` | `bool` |
163
| `null` | `None` |
164
| `undefined` | `None` |
165
| `Array` | `list` |
166
| `Object` | `dict` |
167
168
## Error Handling
169
170
```python
171
import execjs
172
173
try:
174
result = execjs.eval("invalidSyntax(")
175
except execjs.ProgramError as e:
176
print(f"JavaScript error: {e}")
177
178
try:
179
result = execjs.eval("throw new Error('Custom error')")
180
except execjs.ProgramError as e:
181
print(f"JavaScript threw: {e}")
182
183
try:
184
# This will fail if no runtime is available
185
result = execjs.eval("2 + 2")
186
except execjs.RuntimeUnavailableError as e:
187
print(f"No JavaScript runtime available: {e}")
188
```