Node.js / TypeScript · recipe
Read a value from an OPC UA server in Node.js
Read the Value attribute and inspect the whole DataValue that comes back. The status code and both timestamps are on the object, and discarding them is how a collector ends up unable to explain its own numbers.
| Stack | node-opcua |
|---|---|
| Version | 2.181.1 |
The code
const { OPCUAClient, AttributeIds, TimestampsToReturn } = require("node-opcua");
(async () => {
const client = OPCUAClient.create({ endpointMustExist: false });
await client.connect("opc.tcp://opcua.umati.app:4840");
const session = await client.createSession();
const dv = await session.read(
{ nodeId: "i=2258", attributeId: AttributeIds.Value },
TimestampsToReturn.Both
);
console.log("value :", dv.value.value);
console.log("dataType :", dv.value.dataType);
console.log("status :", dv.statusCode.toString());
console.log("source timestamp:", dv.sourceTimestamp);
console.log("server timestamp:", dv.serverTimestamp);
await session.close();
await client.disconnect();
})();
What it prints
value : 2026-09-08T03:44:59.321Z
dataType : 13
status : Good (0x00000000)
source timestamp: 2026-09-08T03:44:59.321Z
server timestamp: 2026-09-08T03:44:59.321Z
Notes
- Ask for TimestampsToReturn.Both while developing, then narrow it. Some PLC-embedded servers populate only ServerTimestamp meaningfully, and you want to discover that early.
- Reads take arrays. One request for two hundred nodes beats two hundred requests, up to the server's operation limit.
- Resolve namespaces with `nsu=` node id syntax or by reading the namespace array, rather than hardcoding `ns=4` and having it shift after a program download.
- Branch on `dv.statusCode.isGood()`. An Uncertain status is a real signal, not a rounding error.
What breaks first
A read returns BadNodeIdUnknown after a server upgrade that worked yesterday
The namespace index shifted. Read the namespace array at connect and resolve indexes from URIs at runtime.
BadNodeIdUnknownThe namespace index shifted. Read the namespace array at connect and resolve indexes from URIs at runtime.
Other recipes in this stack
Concepts on this page
Last verified 7 September 2026 against OPC UA 1.05.07. OPC UA Connect is an educational resource and is not affiliated with the OPC Foundation.