在节点

时间:2015-11-20 03:19:12

标签: node.js

我是Node.js的新手,我创建了一个小的加密脚本。但是,我有问题从另一个函数中的一个函数访问变量

    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());
    }
});

当我运行上面的代码时,我收到一条错误说明:

buffer.js:67     抛出新的TypeError('必须以数字,缓冲区,数组或字符串'开头);

我该如何做到这一点?

1 个答案:

答案 0 :(得分:1)

triplesec.encrypttriplesec.decrypt似乎是一个异步函数。

所以你应该在decrypt回调之后encrypt

也许你应该这样写:

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());
        }
    });

});