开发者

How do I use this function in Node.JS?

//tools.js
function randomString(开发者_Python百科) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomString;
}
exports.randomString = randomString();


//test.js
var tools = require('./tools');
console.log(tools.randomString());

But when I run it, I get this:

[Function: randomString]

How do I actually make it spit out a random string?


exports.randomString = randomString;

or

exports.randomString = function() {....}


Don't know node.js in detail. But

exports.randomString = randomString();

already calls the function and assigns the result to exports.randomString.

To assign the reference you should take away the braces.

Second Bug:

return randomString;

needs to be (watch the case)

return randomstring;

as this is the variable where you build and store your random string.


Are yor sure that your accepted answer fully resolves your problem?

If you do

exports.randomString = randomString();

then you call the random string function exactly once and assign the result to exports.randomString.

Please check and call multiple times

console.log(tools.randomString());

For more advice please read my other answer above. Hope I could help.


use a different name for your result. one which isn't the same as your function's name.

the variable randomstring contains your accumulated result but you return randomString which is just off it by case and is the name of the function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜