{"library":"node-opcua","title":"node-opcua - Pure Node.js OPC UA SDK","description":"node-opcua is a comprehensive, pure JavaScript/TypeScript implementation of the OPC Unified Architecture (OPC UA) stack, designed for Node.js environments. It enables the creation of OPC UA clients, servers, and related tools, facilitating machine-to-machine (M2M) and Industrial IoT (IIoT) communication. The package is actively maintained, with frequent minor and patch releases, currently stable at version 2.169.0, focusing on performance, memory optimization, and OPC UA 1.05 compliance. Key differentiators include its full adherence to the OPC UA specification, a robust architecture for handling large information models, and enterprise-grade support and value-added extensions provided by Sterfive SAS, which also sponsors its long-term development. It supports modern Node.js versions (>=18) and ships with TypeScript types for improved developer experience.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install node-opcua"],"cli":null},"imports":["import { OPCUAClient } from 'node-opcua';","import { OPCUAServer } from 'node-opcua';","import { DataType, AttributeIds } from 'node-opcua';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { OPCUAServer, OPCUAClient, MessageSecurityMode, SecurityPolicy, DataType, Variant, AttributeIds } from \"node-opcua\";\nimport { resolve } from \"path\";\n\n// --- Server Setup ---\nasync function startServer() {\n    // Ensure a 'certificates' directory exists in your project root\n    // For production, manage certificates securely (e.g., via GDS)\n    // This example uses anonymous authentication for simplicity.\n    const server = new OPCUAServer({\n        port: 4334,\n        resourcePath: \"/UA/MySampleServer\",\n        buildInfo: {\n            productName: \"MySampleServer\",\n            buildNumber: \"1234\",\n            buildDate: new Date()\n        },\n        serverInfo: {\n            applicationUri: \"urn:MySampleServer\",\n            productUri: \"urn:MySampleServer\",\n            applicationName: { text: \"MySampleServer\", locale: \"en\" }\n        },\n        securityModes: [MessageSecurityMode.None],\n        securityPolicies: [SecurityPolicy.None],\n        allowAnonymous: true,\n        // Certificate files are needed even with securityMode.None in many setups\n        // The toolkit generates default ones in C:\\Users\\user\\AppData\\Roaming\\node-opcua-default-nodejs\n        // if not provided, but explicitly setting them is good practice for production.\n        // For simplicity in this quickstart, we assume default generation or manual placement.\n    });\n\n    await server.start();\n    console.log(`Server started on port ${server.port}`);\n    console.log(`Server endpointUrl: ${server.endpointUrl}`);\n\n    server.engine.addressSpace?.getFolder(\"ObjectsFolder\")?.addVariable({\n        nodeId: \"ns=1;s=MyDynamicVariable\",\n        browseName: \"MyDynamicVariable\",\n        dataType: DataType.Int32,\n        value: {\n            get: () => new Variant({ dataType: DataType.Int32, value: Math.floor(Math.random() * 100) })\n        }\n    });\n\n    return server;\n}\n\n// --- Client Setup ---\nasync function startClient(endpointUrl: string) {\n    const client = OPCUAClient.create({\n        endpointUrl,\n        securityMode: MessageSecurityMode.None,\n        securityPolicy: SecurityPolicy.None,\n        connectionStrategy: {\n            maxRetry: 0, // No retries for quickstart simplicity\n            initialDelay: 100\n        }\n    });\n\n    try {\n        await client.connect(endpointUrl);\n        console.log(\"Client connected to server.\");\n\n        const session = await client.createSession();\n        console.log(\"Client session created.\");\n\n        // Browse the root folder\n        const browseResult = await session.browse(\"RootFolder\");\n        console.log(\"RootFolder children:\");\n        for (const reference of browseResult.references || []) {\n            console.log(`  - ${reference.browseName.toString()}`);\n        }\n\n        // Read the value of MyDynamicVariable\n        const readValue = await session.read({\n            nodeId: \"ns=1;s=MyDynamicVariable\",\n            attributeId: AttributeIds.Value\n        });\n        console.log(`Value of MyDynamicVariable: ${readValue.value?.value}`);\n\n        await session.close();\n        await client.disconnect();\n        console.log(\"Client disconnected.\");\n\n    } catch (err) {\n        console.error(\"Client error:\", err);\n    }\n}\n\n// --- Main Execution ---\n(async () => {\n    let server: OPCUAServer | null = null;\n    try {\n        server = await startServer();\n        // Give server a moment to fully initialize\n        await new Promise(resolve => setTimeout(resolve, 1000));\n        await startClient(server.endpointUrl!); // Use the server's dynamically assigned endpoint\n    } catch (error) {\n        console.error(\"Error during quickstart execution:\", error);\n    } finally {\n        if (server) {\n            console.log(\"Shutting down server...\");\n            await server.shutdown();\n            console.log(\"Server shut down.\");\n        }\n    }\n})();","lang":"typescript","description":"This example demonstrates how to set up a basic OPC UA server, expose a dynamically updating integer variable, and then connect to it with an OPC UA client to browse its address space and read the variable's value. It uses anonymous authentication and no message security for simplicity. For production use, secure communication with certificates and user authentication is highly recommended.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}