mikuso / ocpp-rpc

A Node.js client & server implementation of the WAMP-like RPC-over-websocket system defined in the OCPP-J protocols.
MIT License
94 stars 28 forks source link

Example for using this package in a project that uses ESM module #67

Closed xiaojieTao closed 10 months ago

xiaojieTao commented 10 months ago

There is no out of box example for using this package in a project that uses ESM module so I edited one of the example in the README:

import express from "express";
let rpc;
async function load() {
    rpc = await import("ocpp-rpc");
};

(async () => {
    await load();
    const app = express();
    const httpServer = app.listen(3000, 'localhost');

    const rpcServer = new rpc.RPCServer();
    httpServer.on('upgrade', rpcServer.handleUpgrade);

    rpcServer.on('client', client => {
        // RPC client connected
        client.call('Say', `Hello, ${client.identity}!`);
    });

    // create a simple client to connect to the server
    const cli = new rpc.RPCClient({
        endpoint: 'ws://localhost:3000',
        identity: 'XYZ123'
    });

    cli.handle('Say', ({params}) => {
        console.log('Server said:', params);
    });

    await cli.connect();
})();
xiaojieTao commented 10 months ago

This also works:

import express from "express";
let rpc;
async function load() {
    rpc = await import("ocpp-rpc");
};

    await load();
    const app = express();
    const httpServer = app.listen(3000, 'localhost');

    const rpcServer = new rpc.RPCServer();
    httpServer.on('upgrade', rpcServer.handleUpgrade);

    rpcServer.on('client', client => {
        // RPC client connected
        client.call('Say', `Hello, ${client.identity}!`);
    });

    // create a simple client to connect to the server
    const cli = new rpc.RPCClient({
        endpoint: 'ws://localhost:3000',
        identity: 'XYZ123'
    });

    cli.handle('Say', ({params}) => {
        console.log('Server said:', params);
    });

    await cli.connect();
mikuso commented 10 months ago

Why not just write import { RPCServer } from 'ocpp-rpc'; ?

I'm not sure what the async import is for.

xiaojieTao commented 10 months ago

Why not just write import { RPCServer } from 'ocpp-rpc'; ?

I'm not sure what the async import is for.

I am beginner to node and JS. Some post from stack overflow said I need to use dynamic import to import CommonJS module into ESM project. I guest either that info is outdated or ocpp-rpc is compatible with both CommonJS and ESM. Is ocpp-rpc a CommonJS module?

mikuso commented 10 months ago

I need to use dynamic import to import CommonJS module into ESM project

I think it's the other way around; You need to use a dynamic import to import ESM modules into a CommonJS project.

Is ocpp-rpc a CommonJS module?

Yes, although this may change at some time in the future in a major version revision.

I'll close this issue for now, as I don't think the readme amendment is required at this time.