Skip to content

Commit 28ffcd0

Browse files
doc: add custom module example
1 parent a429813 commit 28ffcd0

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

example/custom-module/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Using Custom Node Module
2+
3+
This is a basic example of how to use [@sebastianwessel/quickjs](https://github.com/sebastianwessel/quickjs). You can test it out by running:
4+
5+
```sh
6+
bun run example:module
7+
```
8+
9+
from the root of this repository.

example/custom-module/custom.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export const customFn = () => {
2+
return 'Hello from the custom module'
3+
}

example/custom-module/index.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { join } from 'node:path'
2+
import { dirname } from 'node:path'
3+
import { fileURLToPath } from 'node:url'
4+
import { quickJS } from '@sebastianwessel/quickjs'
5+
6+
// General setup like loading and init of the QuickJS wasm
7+
// It is a ressource intensive job and should be done only once if possible
8+
const { createRuntime } = await quickJS()
9+
10+
const __dirname = dirname(fileURLToPath(import.meta.url))
11+
const customModuleHostLocation = join(__dirname, './custom.js')
12+
13+
// Create a runtime instance each time a js code should be executed
14+
const { evalCode } = await createRuntime({
15+
nodeModules: {
16+
// module name
17+
'custom-module': {
18+
// key must be index.js, value file content of module
19+
'index.js': await Bun.file(customModuleHostLocation).text(),
20+
},
21+
},
22+
})
23+
24+
const result = await evalCode(`
25+
import { customFn } from 'custom-module'
26+
27+
const result = customFn()
28+
29+
console.log(result)
30+
31+
export default result
32+
`)
33+
34+
console.log(result) // { ok: true, data: 'Hello from the custom module' }

0 commit comments

Comments
 (0)