Im new to using classes in JS and been trying to find the best practices for it and was wondering how requires work when using it in the class.
Say I wanted to create an IoT Connection class to use to make connection to the azure iot hub. In order to make connections i need some requires to get the function getClientFromConnectionString
.
var Protocol = require('azure-iot-device-amqp').Amqp;
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;
class IoT_Connection {
constructor(_deviceName, _securityKey1, _securityKey2) {
this.deviceName = _deviceName;
this.securityKey1 = _securityKey1;
this.securityKey2 = _securityKey2;
}
}
module.exports = IoT_Connection;
var conn = new IoT_Connection("z", "x", "y");
What happens when i create a new instance of the class? Does the require load only once or would be a problem if i was making hundreds of connections every few minutes?
Is there a better approach to this problem?
Yes; whenever your run your nodejs server your code is interpreted by javascript engine(in this case the very V8 engine) it will interpret your code. The file which is require by any of the starting file(server.js or app.js) will be interpreted and the require statements will be executed only once.
So,
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;
will make only one connection.
To understand better of 'how module.exports and require work' create an empty file and do some console.log('foo')
in there and require
it in your existing code.