@@ -4,14 +4,112 @@ title: How to run JSPython interpreter
4
4
sidebar_label : JSPython interpreter
5
5
---
6
6
7
+ ## Install JS Python Interpreter
8
+
9
+ ```
10
+ npm i jspython-interpreter
11
+ ```
12
+
7
13
## How to use JS Python Interpreter
8
14
15
+ #### ECMAScript module
16
+
17
+ ``` js
18
+ import { jsPython } from ' jspython-interpreter' ;
19
+ ```
20
+
21
+ #### CommonJS module
22
+
23
+ ``` js
24
+ const jsPython = require (' jspython-interpreter' ).jsPython ;
25
+ ```
26
+
27
+ #### Append ` <script> ` in html
28
+
29
+ ``` html
30
+ <script type =" text/javascript" src =" https://cdn.jsdelivr.net/npm/jspython-interpreter/dist/jspython-interpreter.min.js" ></script >
31
+
32
+ <script >
33
+ const jsPython = window .jspython .jsPython
34
+ </script >
35
+ ```
36
+
37
+ ## Create interpreter and evaluate script.
38
+
39
+ ``` js
40
+ const script = `
41
+ x = 2 + 3
42
+ x
43
+ ` ;
44
+ const interpreter = jsPython ();
45
+ interpreter .evaluate (script).then (res => {
46
+ consoe .log (res); // 5
47
+ })
48
+ ```
49
+
9
50
## Expose functions for JSPython import
10
51
11
- ### In browser app
52
+ ### Install needed modules localy using ` npm install moduleName ` command.
53
+
54
+ ### Register package loader function to use js libraries in your script.
55
+ #### In browser app
56
+ ``` js
57
+ import * as papaparse from ' papaparse' ;
58
+ import * as dataPipe from ' datapipe-js' ;
59
+
60
+ const AVAILABLE_PACKAGES = {
61
+ papaparse,
62
+ ' datapipe-js' : dataPipe
63
+ };
64
+
65
+ interpreter .registerPackagesLoader ((packageName ) => {
66
+ return AVAILABLE_PACKAGES [packageName];
67
+ });
68
+
69
+ ```
70
+
71
+ #### In NodeJS
72
+ ``` js
73
+ interpreter .registerPackagesLoader ((packageName ) => {
74
+ return require (packageName);
75
+ });
76
+ ```
77
+ ### Import js libraries in script
78
+ ``` js
79
+ import axios // import library
80
+ from fs import readFileSync as rfs , writeFileSync // import only methods from library
81
+ import json5 as JSON5 // use as to provide appropriate name for lib.
82
+ res = axios .get (" data/url" )
83
+ ```
84
+
85
+ ## Register to the global scope
86
+ #### Make custom function available in script.
87
+ ``` js
88
+ interpreter .addFunction (' greeting' , (name ) => {
89
+ return ' Hello ' + name + ' !' ;
90
+ });
12
91
13
- ### In NodeJS
92
+ await interpreter .evaluate (' greeting("John")' ) // Hello John.
93
+ ```
14
94
15
- ## Register functions to the global scope
95
+ #### Make object availabel in script
96
+ ``` js
97
+ interpreter .assignGlobalContext ({
98
+ method1 : () => 1 ,
99
+ prop1: 2
100
+ })
101
+ const script = `
102
+ v = method1() + prop1
103
+ v
104
+ `
105
+ await interpreter .evaluate (script) // 3.
106
+ ```
16
107
17
108
## Provide evaluation context
109
+ ``` js
110
+ const script = `
111
+ v = prop1 + prop2
112
+ v
113
+ `
114
+ await interpreter .evaluate (script, {prop1: 3 , prop2: - 2 }) // 1
115
+ ```
0 commit comments