Repository: node-opcua/node-opcua

Issue #573: How to package this module into a js file that can be used by the browser?
Created: 2018-12-10T09:37:09Z
I'm submitting a ...  (check one with "x")

( ) bug report => search github for a similar issue or PR before submitting
( ) feature request
( ) support request => Please do not submit support request here, instead see use

use gitter or stackoverflow for community support, or
contact Sterfive for commercial support



Current behavior

Expected behavior

Minimal reproduction of the problem with instructions












...
What is the motivation / use case for changing the behavior?

Please tell us about your environment:



( ) my request is related to node-opcua acting as a  OPCUA CLIENT


( )  my request is related to node-opcua acting as a OPCUA SERVER


( ) I have installed node-opcua from source ( using git clone)


( ) I have installed node-opcua as a package ( using npm install )


( ) I am using an application that uses node-opcua

( ) node-red
( ) other : please specify



Device: _____


OS version: _____

( ) Windows : version : _________
( ) Linux   : version : _________
( ) MacOs   : version : _________
( ) Raspbian: version : _________
( ) Other   : specify :



Description of the other OPCUA system I am trying to connect to:

Name:_________
Version:_________
Manufacturer/Software vendor:_________
link : https://



node-opcua version:  :





Node:
node --version =



Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Duplicate issue #733: Errors on node-opcua-pki when creating client in Typescript in an Angular project
Created: 2020-02-14T09:15:34Z
Current behavior
Lots of errors, starting with:
ERROR in ./node_modules/node-opcua-pki/dist/lib/misc/install_prerequisite.js
Module not found: Error: Can't resolve 'child_process' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules\node-opcua-pki\dist\lib\misc'
ERROR in ./node_modules/node-opcua-pki/dist/lib/pki/toolbox.js
Module not found: Error: Can't resolve 'child_process' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules\node-opcua-pki\dist\lib\pki'
ERROR in ./node_modules/multicast-dns/index.js
Module not found: Error: Can't resolve 'dgram' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules\multicast-dns'
ERROR in ./node_modules/node-opcua-hostname/dist/hostname.js
Module not found: Error: Can't resolve 'dns' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules\node-opcua-hostname\dist'
ERROR in ./node_modules/node-opcua-pki/dist/lib/misc/hostname.js
Module not found: Error: Can't resolve 'dns' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules\node-opcua-pki\dist\lib\misc'
ERROR in ./node_modules/@nodelib/fs.scandir/out/adapters/fs.js
Module not found: Error: Can't resolve 'fs' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules@nodelib\fs.scandir\out\adapters'
ERROR in ./node_modules/@nodelib/fs.stat/out/adapters/fs.js
Module not found: Error: Can't resolve 'fs' in 'C:\Work\Experiments\Angular7_OPC1\OPC1\node_modules@nodelib\fs.stat\out\adapters'
Describe the bug
I have implemented a client according to your code in:
https://github.com/node-opcua/node-opcua/blob/master/documentation/creating_a_client_typescript.md
This is implemented in Typescript in an Angular9 project: see below for code.
During compile of the project ('ng serve -o') the errors are produced.
To Reproduce
Steps to reproduce the behavior:

ng serve -o

Expected behavior
No errors during build.


(x) my request is related to node-opcua acting as a  OPCUA CLIENT


( )  my request is related to node-opcua acting as a OPCUA SERVER


( ) I have installed node-opcua from source ( using git clone)


(x) I have installed node-opcua as a package ( using npm install )


( ) I am using an application that uses node-opcua


OS version: _____

( ) Windows : version : 10



Description of the other OPCUA system I am trying to connect to:
Does not build, so no connection tried


node-opcua version:  :
"node-opcua": "^2.5.0-alpha.9"


Node:
Node.js v12.14.1.


===== Code used:
import { Injectable } from '@angular/core';
import {
  OPCUAClient,
  MessageSecurityMode,
  SecurityPolicy,
  AttributeIds,
  makeBrowsePath,
  ClientSubscription,
  TimestampsToReturn,
  MonitoringParametersOptions,
  ReadValueIdLike,
  ClientMonitoredItem,
  DataValue
} from "node-opcua";


@Injectable({
  providedIn: 'root'
})

export class OpcDataService {

  data1: number = 0;

  
  connectionStrategy = {
    initialDelay: 1000,
    maxRetry: 1
  };
  options = {
    applicationName: "MyClient",
    connectionStrategy: this.connectionStrategy,
    securityMode: MessageSecurityMode.None,
    securityPolicy: SecurityPolicy.None,
    endpoint_must_exist: false
  };
  client = OPCUAClient.create(this.options);
  endpointUrl = "opc.tcp://127.0.0.1:4840";

  constructor() { 
    setInterval(() => {this.data1++}, 1000);
  }

 
  public OpcService = async () => {  

    try {
      // See: https://github.com/node-opcua/node-opcua/blob/master/documentation/creating_a_client_typescript.md
      // step 1 : connect to
      console.log('=============== step 1 : connect to');
      await this.client.connect(this.endpointUrl);
      console.log("connected !");
  
      // step 2 : createSession
      console.log('=============== step 2 : createSession');
      const session = await this.client.createSession();
      console.log("session created !");
  
      // step 3 : browse
      console.log('=============== step 3 : browse');
      const browseResult = await session.browse("RootFolder");

      console.log("references of RootFolder :");
      for (const reference of browseResult.references) {
        console.log("   -> ", reference.browseName.toString());
      }
  
      // step 4 : read a variable with readVariableValue
      console.log('=============== step 4 : read a variable with readVariableValue');
      const dataValue2 = await session.readVariableValue(
        "ns=3;s=Scalar_Simulation_Double"
      );
      console.log(" value = ", dataValue2.toString());

      // step 4' : read a variable with read
      console.log('=============== step 4a : read a variable with read');
      const maxAge = 0;
      const nodeToRead = {
        nodeId: "ns=3;s=Scalar_Simulation_String",
        attributeId: AttributeIds.Value
      };
      const dataValue = await session.read(nodeToRead, maxAge);
      console.log(" value ", dataValue.toString());
  
      // step 5: install a subscription and install a monitored item for 10 seconds
      console.log('=============== step 5: install a subscription and install a monitored item for 10 seconds');
      const subscription = ClientSubscription.create(session, {
        requestedPublishingInterval: 1000,
        requestedLifetimeCount: 100,
        requestedMaxKeepAliveCount: 10,
        maxNotificationsPerPublish: 100,
        publishingEnabled: true,
        priority: 10
      });

      subscription
        .on("started", function() {
          console.log(
            "subscription started for 2 seconds - subscriptionId=",
            subscription.subscriptionId
          );
        })
        .on("keepalive", function() {
          console.log("keepalive");
        })
        .on("terminated", function() {
          console.log("terminated");
        });

      // install monitored item

      const itemToMonitor: ReadValueIdLike = {
        nodeId: "ns=3;s=Scalar_Simulation_Float",
        attributeId: AttributeIds.Value
      };
      const parameters: MonitoringParametersOptions = {
        samplingInterval: 100,
        discardOldest: true,
        queueSize: 10
      };

      const monitoredItem = ClientMonitoredItem.create(
        subscription,
        itemToMonitor,
        parameters,
        TimestampsToReturn.Both
      );

      monitoredItem.on("changed", (dataValue: DataValue) => {
        console.log(" value has changed : ", dataValue.value.toString());
      });

      async function timeout(ms: number) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      await timeout(10000);

      console.log("now terminating subscription");
      await subscription.terminate();
  
      // step 6: finding the nodeId of a node by Browse name
      console.log('=============== step 6: finding the nodeId of a node by Browse name');
      const browsePath = makeBrowsePath(
        "RootFolder",
        "/Objects/Server.ServerStatus.BuildInfo.ProductName"
      );
      
      const result = await session.translateBrowsePath(browsePath);
      const productNameNodeId = result.targets[0].targetId;
      console.log(" Product Name nodeId = ", productNameNodeId.toString());
  
      // close session
      console.log('=============== step 7: close session');
      await session.close();
  
      // disconnecting
      console.log('=============== step 8: disconnecting');
      await this.client.disconnect();
      console.log("done !");

    } catch(err) {
      console.log("An error has occured : ",err);
    }

  };
}

Closing comment (2020-02-15T23:21:28Z): duplicates #573 #423
node-opcua cannot be used in a webbrowser application as it relies on features (sockjets/ filesystem/crypto) which are only available on nodejd ( in the backend)