bshah
bshah

Reputation: 140

Access variable outside function in Node

I've created a small encryption script. However, I'm having issues accessing a variable from one function in another function

    var triplesec = require('triplesec');

var data = 'secretthings'
// Encrypt Function
triplesec.encrypt({
    key: new triplesec.Buffer('secretkey'),
    data: new triplesec.Buffer(data),
}, function (err, buff) {
    if(!err) {
        global.data = buff.toString('hex')
        //console.log(buff.toString('hex'))
    }
});

// Decrypt Function
triplesec.decrypt({
    data: new triplesec.Buffer(global.data, "hex"),
    key: new triplesec.Buffer('secretkey')
}, function (err, buff) {
    if(!err) {
        console.log(buff.toString());
    }
});

When I run the above code, I get an error stating:

buffer.js:67 throw new TypeError('must start with number, buffer, array or string');

How can I accomplish this?

Upvotes: 0

Views: 713

Answers (1)

sjfkai
sjfkai

Reputation: 98

triplesec.encryptand triplesec.decrypt seems like a asynchronous function.

So you should decrypt after encrypt callback.

Maybe you should write like this :

var triplesec = require('triplesec');

// Encrypt Function
triplesec.encrypt({
    key: new triplesec.Buffer('secretkey'),
    data: new triplesec.Buffer('secretthings'),
}, function (err, buff) {
    if(!err) {
        var ciphertext = buff.toString('hex')
        console.log(buff.toString('hex'))
    }

    // Decrypt Function
    triplesec.decrypt({
        data: new triplesec.Buffer(ciphertext, "hex"),
        key: new triplesec.Buffer('secretkey')
    }, function (err, buff) {
        if(!err) {
            console.log(buff.toString());
        }
    });

});

Upvotes: 1

Related Questions