简体   繁体   中英

How do I use this function in Node.JS?

//tools.js
function randomString() {
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM