Any had tried that read the AUTH in NodeJs From a .txt file?

@vshymanskyy
Anybody had some similar try to read the AUTH for NodeJs From a .txt file?
i want to put the the auth of node js device to a txt file and cat it and save it to AUTH and use it for connection. this made my Node more Dynamic.
but oi had some try as below code: But it doesn’t work

var exec = require('child_process').exec, child;

function function1() {
child = exec("cat /home/pi/Blynk/auth.txt", function (error, stdout, stderr) {
 var AUTH = stdout;
  console.log(AUTH);
});
}

function function2() {
var Blynk= require('blynk-library');
console.log(AUTH);
var blynk = new Blynk.Blynk(AUTH, options = { connector : new Blynk.TcpClient( options = { addr:"127.0.0.1", port:8442 } ) });
}

function1();
function2();

Man, this is just ordinary JS programming question. It has nothing to do with Blynk.
You need to understand how JavaScript callbacks work at least…
And… use console.log() to understand what data is passed and when functions get called. This doesn’t work the same way as arduino code.

2 Likes

But, it’s really good concept once you get used to it.

1 Like
undefined

Connecting to TCP: 192.168.1.10 8442
Connected
/node_modules/blynk-library/blynk.js:554
      self.sendRsp(MsgType.LOGIN, 1, self.auth.length, self.auth);
                                               ^

TypeError: Cannot read property 'length' of undefined
    at /node_modules/blynk-library/blynk.js:554:48
    at Socket.<anonymous> (/node_modules/blynk-library/blynk-node.js:55:7)
    at Object.onceWrapper (events.js:314:30)
    at emitNone (events.js:110:20)
    at Socket.emit (events.js:207:7)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1162:10)

You have to define var AUTH outside the function1, as a global variable.

1 Like

it says connected but The error is:

@Gicus

what about This:

var exec = require('child_process').exec, child;
 var AUTH;

function function1() {
child = exec("cat /home/pi/Blynk/auth.txt", function (error, stdout, stderr) {
 AUTH = stdout;
  console.log(AUTH);
});
}

function function2() {
var Blynk= require('blynk-library');
console.log(AUTH);
var blynk = new Blynk.Blynk(AUTH, options = { connector : new Blynk.TcpClient( options = { addr:"127.0.0.1", port:8442 } ) });
}

function1();
function2();

I still don’t see that you understand JS asynchronous nature…
In your code AUTH won’t be assigned BEFORE it is used in function2.
also, why would one ever need this ugly exec("cat ... when there’s propper fs API in Node.js: http://lmgtfy.com/?q=fs+node.js or https://www.w3schools.com/nodejs/nodejs_filesystem.asp

ALSO (just first links from google):
http://nodeguide.com/beginner.html
https://nodeschool.io/
https://www.w3schools.com/nodejs/

2 Likes

@vshymanskyy
that was great.