Question

I created on the module util.js a function myHash() for reuse in different parts of my code but not working.

Error message: this._binding.update(data, encoding); Not a string or buffer.

app.js

...
GLOBAL.util = require('./util');
GLOBAL.dateFormat = util.dateFormat;
GLOBAL.myHash = util.myHash; /***** My function *****/
...

app.post('/test', function(req, res){
    ...
    var pass_shasum = myHash('test');
...

util.js

var crypto = require('crypto');
function myHash(msg) {
    return crypto.createHash('sha256').update(msg).digest('hex');
}

exports.util = {
    ...
    myHash: myHash(),
    ...
};

Any suggestions?


Solution:

Modify util.js

var crypto = require('crypto');

/* Define var */
var myHash = function (msg) {
    return crypto.createHash('sha256').update(msg).digest('hex');
};

module.exports = {
    ...
    myHash: myHash, /* Is a variable not a method. Thanks @robertklep */
    ...
};
Was it helpful?

Solution

You shouldn't execute the function in your exports statement (the msg argument will be undefined which indeed is not a string or a buffer):

exports.util = {
    ...
    myHash: myHash, // don't use myHash()
    ...
};

Also, when you export your code like this, you have to require it like this:

GLOBAL.util = require('./util').util;

(although I would suggest not using globals).

If you don't want the extra .util, export like this:

module.exports = {
  ...
  myHash : myHash,
  ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top