1

Every time I try to assign a variable from a class I cannot use it.

Then when I make a small sample code to put on-line, the functions work in the small example. How do I log a variable to the screen after returning it from a class?

In the small code examples it works, in the larger code to actually do things, I receive an undefined reference error probably as the functions take longer to run.

With a main.js like:

var KeyPair = require('./Keypair');
var Q = require("q");
path_k = __dirname + "/user_p_key_1.txt";
var pair = new KeyPair();

var p = pair.getPublicKey(path_k);
console.log(p + " sig_1"); // error: logs "undefined sig_1" instead of key.

Q.fcall(p = pair.getPublicKey(path_k))
.then(console.log(p + " sig_2")); // error: logs "undefined sig_2" instead of key.

The output is:

undefined sig_1
undefined sig_2
Key fileread successfully
Is it a valid public key?
true
Key:GAVAPNTBWRG337JWZYLR2SBPD5KFA2PPXDMN4HEEBLWSZQIKTPOEFZL6
Key fileread successfully
Is it a valid public key?
true
Key:GAVAPNTBWRG337JWZYLR2SBPD5KFA2PPXDMN4HEEBLWSZQIKTPOEFZL6
Key fileread successfully
Is it a valid public key?
true
Key:GAVAPNTBWRG337JWZYLR2SBPD5KFA2PPXDMN4HEEBLWSZQIKTPOEFZL6

Using the Keypair.js Class:

var fs = require('fs');
var StellarBase = require('stellar-base');
var StellarSdk = require('stellar-sdk');

// A class for referencing KeyPair methods to read and write from files
var method = KeyPair.prototype;

function KeyPair() {
}

method.getPublicKey = function(path_k) {

    // Read PublicKey from filename
    fs.open(path_k, 'r', function(err, fd) {  
        if (err) {
            throw 'could not open file: ' + err;
        }
        // Buffer Array Initialised for the Public Key
        // write the contents of the buffer, from position 0 to the end, to the file descriptor returned in opening our file
        var arr = [null,null,null,null,null,null,null,null,null,null,null,null,
                    null,null,null,null,null,null,null,null,null,null,null,null,
                    null,null,null,null,null,null,null,null];
        var buffer_k = Buffer.from(arr);
        fs.read(fd, buffer_k, 0, buffer_k.length, null, function(err) {
            if (err) throw 'error reading file: ' + err;
            fs.close(fd, function() {
                //console.log('Key fileread successfully');
                var user_encoded_k = StellarBase.StrKey.encodeEd25519PublicKey(buffer_k);
                //console.log('Is it a valid public key?');
                //console.log(StellarBase.StrKey.isValidEd25519PublicKey(user_encoded_k));
                //console.log('Key:' + user_encoded_k);
                return user_encoded_k
            });
        });
    });
};

Reading in a Public Key "user_p_key_1.txt":

*¶a´M½ý6ÎH/TPiï¸ØÞ„
í,Á
݆B

The key is a for a test-server.

Also, I created the simplified Keypair.js as below to show that my code isn't working, and the sample Keypair.js worked different to the Keypair.js above and assign the variable and logged it to screen correctly.

Simplified Keypair.js

var fs = require('fs');

// A class for referencing KeyPair methods to read and write from files
var method = KeyPair.prototype;


function KeyPair() {
}

method.getPublicKey = function(value) {
    return 1
};

module.exports = KeyPair;

I considered it was perhaps something to do with the asynchronous interpreter not being finished with the function when the variable is called so I implemented it afterwards in promises, and to my disbelief p still returned undefined. How do we assign a variable from a class functions and use it in Node.JS?

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Julian Wise
  • 380
  • 1
  • 3
  • 16
  • 2
    You are right in that it it's an async issue, you aren't using `Q` properly either. – MinusFour Jan 02 '18 at 02:41
  • Apologies! I tried to modify an example from the [Q Github Page](https://github.com/kriskowal/q). Would you know where I could by chance find a reference to the proper use of Q for using variable outputs? – Julian Wise Jan 02 '18 at 02:52
  • 1
    Your `getPublicKey` needs to return a promise, [the github page](https://github.com/kriskowal/q#using-deferreds) has examples of how to do it through deferreds or the promise api (use this preferably). – MinusFour Jan 02 '18 at 03:48
  • I don't think I'd want to include it in the function definition for `getPublicKey`, as the goal is get a variable from a function and then use the variable after getting it from the `getPublicKey` function. That way another function can utilize the return variable. – Julian Wise Jan 02 '18 at 04:49
  • 1
    Julian Wise, your function isn't returning anything though because it's async. That's why it needs to return a promise. It's important to read [this](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – MinusFour Jan 02 '18 at 04:57
  • 1
    @KARTHIKEYAN.A, I don't think that arbitrary changing valid and widely used English words to some other version is a good editing strategy. Fixing typos is OK and welcome. Changing spelling to your preferred one is probably not. Also I don't think that adding as much tags as possible is beneficial. I think tags should be added to improve 1) discoverability of the question by the potential **_relevant_** experts 2) discoverability of future people searching for similar questions. If adding tag doesn't help that - it should not be added. To sum up: edit only if it really improves quality! – SergGr Jan 02 '18 at 08:09
  • Ok, Now i understand @SergGr – KARTHIKEYAN.A Jan 02 '18 at 08:11

0 Answers0