11# @deephaven/jsapi-nodejs
22
33Deephaven utils for consuming Jsapi from a server from a nodejs app. It can
4- optionally convert the server module format from ` ESM ` -> ` CJS ` or ` CJS ` -> ` ESM `
5- if the server and consumer don't use the same module format.
4+ provide the api as a ` CJS ` or ` ESM ` module.
65
76## Install
87
@@ -12,21 +11,57 @@ npm install --save @deephaven/jsapi-nodejs
1211
1312## Usage
1413
14+ ### Download jsapi as ` ESM ` Module
15+
1516``` typescript
1617import fs from ' node:fs' ;
1718import path from ' node:path' ;
19+ import type { dh as DhType } from ' @deephaven/jsapi-types'
1820
1921import { loadModules } from ' @deephaven/jsapi-nodejs' ;
2022
2123const tmpDir = path .join (__dirname , ' tmp' );
2224
23- // Download jsapi `ESM` files from DH Community server and export as `CJS` module.
24- const dhc = await loadModules ({
25+ const dhc = (
26+ await loadModules <{ default: typeof DhType }>({
27+ serverUrl: new URL (' http://localhost:10000' ),
28+ serverPaths: [' jsapi/dh-core.js' , ' jsapi/dh-internal.js' ],
29+ storageDir: tmpDir ,
30+ targetModuleType: ' esm' ,
31+ download: true ,
32+ })
33+ ).default ; // The dh instance will be exported on the .default property
34+ ```
35+
36+ ### Download jsapi as ` CJS ` Module
37+
38+ ``` typescript
39+ const dhc = await loadModules <typeof DhType >({
2540 serverUrl: new URL (' http://localhost:10000' ),
2641 serverPaths: [' jsapi/dh-core.js' , ' jsapi/dh-internal.js' ],
27- download: true ,
2842 storageDir: tmpDir ,
29- sourceModuleType: ' esm' ,
3043 targetModuleType: ' cjs' ,
44+ // Provide a post-download transformation callback. The jsapi is an `ESM`
45+ // module on the server, so we have to replace some things to make it `CJS`
46+ // compliant.
47+ download : (serverPath , content ) => {
48+ if (serverPath === ' jsapi/dh-core.js' ) {
49+ return content
50+ .replace (
51+ ` import {dhinternal} from './dh-internal.js'; ` ,
52+ ` const {dhinternal} = require("./dh-internal.js"); ` ,
53+ )
54+ .replace (` export default dh; ` , ` module.exports = dh; ` )
55+ }
56+
57+ if (serverPath === ' jsapi/dh-internal.js' ) {
58+ return content .replace (
59+ ` export{__webpack_exports__dhinternal as dhinternal}; ` ,
60+ ` module.exports={dhinternal:__webpack_exports__dhinternal}; ` ,
61+ )
62+ }
63+
64+ return content
65+ }
3166});
3267```
0 commit comments