node-opcua Service Register Node

raw JSON →
2.169.0 verified Thu Apr 23 auth: no javascript

The `node-opcua-service-register-node` package is a module within the comprehensive `node-opcua` SDK, a pure Node.js and TypeScript implementation of the OPC UA specification. The SDK is designed for building high-performing asynchronous applications, leveraging Node.js's capabilities. It adheres to a 'Perpetual Beta' model, with new enhanced versions released approximately every two weeks, ensuring continuous improvement and community testing. The project emphasizes quality with over 3500 unit tests and 93% code coverage. This specific module primarily defines the data structures and message types for the OPC UA RegisterNodes Service, which allows OPC UA clients to register NodeIds with a server for more efficient, repeated access operations. The current stable version of the `node-opcua` ecosystem is 2.169.0.

error Cannot find module 'node-opcua'
cause The 'node-opcua' package or its sub-modules are not installed or incorrectly referenced.
fix
Ensure the package is installed: npm install node-opcua or npm install node-opcua-service-register-node. Verify correct import paths in your code.
error error TS2307: Cannot find module 'node-opcua'.
cause TypeScript compiler cannot locate the type definitions for the 'node-opcua' package.
fix
Ensure 'node-opcua' is installed. TypeScript types are bundled with the library, so a correct installation should resolve this. Check your tsconfig.json for moduleResolution settings.
error [NODE-OPCUA-W33] client : server token creation date exposes a time discrepancy of [...] the remote server clock doesn't match this computer date !
cause There is a significant time difference between the OPC UA client and server machines.
fix
Synchronize the system clocks of both the client and server machines using Network Time Protocol (NTP) or similar methods to ensure accurate timekeeping.
error OPCUA Server failed to start: Error: EACCES: permission denied, listen 0.0.0.0:4840
cause The server attempted to listen on a privileged port (e.g., below 1024 on Linux) or a port already in use, without sufficient permissions.
fix
Use a non-privileged port (e.g., 4334 as in the quickstart) or ensure the process has the necessary permissions to bind to the desired port.
breaking Version 2.168.0 introduced a full migration of core packages from older `async` and `lodash` utilities to native modern JavaScript patterns. This may cause breaking changes in applications that directly relied on or extended `node-opcua`'s internal use of these libraries.
fix Review custom codebases for direct dependencies or deep integrations with `node-opcua` internals that might have used `async` or `lodash`. Update code to use native JavaScript asynchronous patterns and utilities.
breaking In version 2.165.0, a bug was fixed where calling `setValueFromSource()` on a `UAVariable` containing a bound extension object with `Date`, `NodeId`, `QualifiedName`, `LocalizedText`, `DiagnosticInfo`, or array fields could lead to silent data corruption.
fix Upgrade to v2.165.0 or newer. Review any code paths that use `setValueFromSource()` with extension objects and verify data integrity after the update.
breaking Version 2.123.0 removed `Basic128Rsa15` and `Basic256` as default security policies for the OPC UA server, making `Aes256_Sha256_RsaPss` the new default. Clients or servers configured to exclusively use the deprecated policies without explicit configuration will fail to connect.
fix Ensure your clients and servers are configured to use modern security policies like `Aes256_Sha256_RsaPss`. If backward compatibility is strictly required, explicitly specify the older security policies in the `OPCUAServer` constructor's `securityPolicies` parameter.
gotcha Node.js versions newer than 18.11.1 or 20.11.1 require a special flag (`--security-revert=CVE-2023-46809`) to re-enable PKCS1 padding due to its reintroduction in `node-opcua` v2.123.0. Without this flag, cryptographic operations requiring PKCS1 padding may fail.
fix When running Node.js applications using `node-opcua` on affected Node.js versions, include the `--security-revert=CVE-2023-46809` flag in the Node.js command line arguments.
gotcha Version 2.123.0 introduced improved clock synchronization checks. Clients will now log a warning (`[NODE-OPCUA-W33]`) in the console if a significant time discrepancy is detected between the client and server clocks, which can affect security token renewal and lead to disconnections.
fix Ensure that both OPC UA client and server machines have their system clocks accurately synchronized (e.g., using NTP). While the client can now use its own time for token renewal, clock discrepancies are a common source of connection issues and should be resolved.
gotcha The OPC UA SDK, including its certificate management (v2.164.2, v2.167.0) and crypto libraries (v2.165.2+), frequently evolves to address security and compatibility. OpenSSL 3.5+ compatibility updates in v2.165.2+ are crucial for newer Node.js versions. Incorrect certificate handling is a common pitfall.
fix Carefully manage certificate generation, private keys, and trust lists. Always verify that your certificate chains are correctly installed and trusted by both client and server. Stay updated with `node-opcua-pki` and `node-opcua-crypto` versions to ensure compatibility with your Node.js and OpenSSL environment.
npm install node-opcua-service-register-node
yarn add node-opcua-service-register-node
pnpm add node-opcua-service-register-node

This quickstart demonstrates how to set up a minimal `node-opcua` server and client, and then shows how to construct a `RegisterNodesRequest` object using types provided by this package for registering NodeIds with the server to optimize subsequent access.

import { OPCUAServer, OPCUAClient, MessageSecurityMode, SecurityPolicy, UserTokenType, NodeId, resolveNodeId } from 'node-opcua';
import { RegisterNodesRequest, RegisterNodesResponse } from 'node-opcua-service-register-node';

async function startOpcUaExample() {
  // 1. Setup a simple OPC UA Server
  const server = new OPCUAServer({
    port: 4334,
    resourcePath: '/UA/MyServer',
    buildInfo: {
      productName: 'MySampleServer',
      buildNumber: '1234',
      buildDate: new Date()
    }
  });

  await server.initialize();
  const addressSpace = server.engine.addressSpace;
  if (!addressSpace) { throw new Error('AddressSpace not initialized'); }

  const device = addressSpace.getFolder('ObjectsFolder')?.addFolder({
    browseName: 'MyDevice'
  });

  if (device) {
    device.addVariable({
      browseName: 'Temperature',
      nodeId: 's=TemperatureSensor1',
      dataType: 'Double',
      value: { get: () => new Variant({ dataType: DataType.Double, value: 25.5 }) }
    });
    console.log('Server initialized with a Temperature variable.');
  }
  
  await server.start();
  console.log(`Server is running at ${server.endpoints[0]?.endpointDescriptions()[0]?.endpointUrl}`);

  // 2. Setup a simple OPC UA Client and demonstrate RegisterNodesRequest structure
  const client = OPCUAClient.create({
    endpointUrl: server.endpoints[0]?.endpointDescriptions()[0]?.endpointUrl,
    securityMode: MessageSecurityMode.None,
    securityPolicy: SecurityPolicy.None,
    connectionStrategy: { maxRetry: 0 }
  });

  try {
    await client.connect(server.endpoints[0]?.endpointDescriptions()[0]?.endpointUrl ?? '');
    console.log('Client connected to server.');

    const session = await client.createSession({
      userIdentity: { type: UserTokenType.Anonymous }
    });
    console.log('Client session created.');

    // Create a RegisterNodesRequest (this package provides the type definition)
    const nodesToRegister = [
      resolveNodeId('s=TemperatureSensor1'),
      new NodeId('ns=1;s=AnotherNode') // Example of another node
    ];
    
    const registerRequest = new RegisterNodesRequest({
      nodesToRegister: nodesToRegister
    });

    console.log('Constructed RegisterNodesRequest:', JSON.stringify(registerRequest.toJSON(), null, 2));
    
    // In a real client, you would send this request via session.performMessage or similar:
    // const response: RegisterNodesResponse = await session.registerNodes(registerRequest.nodesToRegister);
    // console.log('RegisterNodes response:', response);

    await session.close();
    await client.disconnect();
    console.log('Client disconnected.');

  } catch (err) {
    console.error('Client error:', err);
  } finally {
    await server.shutdown();
    console.log('Server shut down.');
  }
}

startOpcUaExample().catch(console.error);