вызвать функцию из другого файла и получить случайный результат для каждого вызова - PullRequest
0 голосов
/ 15 сентября 2018

У меня есть файл random.js, содержащий его, чтобы получить случайный поддельный ip

exports.ip = function () {
    let random = (Math.floor(Math.random() * 255) + 1)+"."+(Math.floor(Math.random() * 255) + 0)+"."+(Math.floor(Math.random() * 255) + 0)+"."+(Math.floor(Math.random() * 255) + 0); 
    return random
}

и я вызываю переменную в файле send.js для замены строки {randomip}

let replace_tag = function (to) {

    config.message.subject = config.message.subject
        .replace("{randomip}", random.ip)
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromname = config.message.fromname
        .replace("{randomip}", random.ip)
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromemail = config.message.fromemail
        .replace("{randomip}", random.ip)
        .replace("{email}", to)
        .replace("{date}", random.date);

}

но он будет выдавать только один сгенерированный ip, я хочу, чтобы он генерировал случайный каждый раз, когда он вызывается, будет выдавать разные значения

Я попытался вставить его в цикл, но все еще не работает

Я вызываю функцию замены в другой функции, затем вводю ее в цикл, как этот

let kirim = function (to) {

    replace_tag(to);

    let message = {
        from: config.message.fromname+'<'+config.message.fromemail+'>',
        to: to,
        subject: config.message.subject,
        text: config.message.text,
        html: html
    };

    transporter.sendMail(message, (error, info) => {
        if (error) {
             return console.log(error.response)
        }
        console.log('Message sent: ',info.accepted);
    });
};


(async () => {

    for (var i in list) {

        kirim(list[i]);
        await delay(config.send.delay*1000); 

    }

})();

Ответы [ 3 ]

0 голосов
/ 15 сентября 2018
function getRandomIp() {
    return (Math.floor(Math.random() * 255) + 1)+"."+(Math.floor(Math.random() * 255) + 
    0)+"."+(Math.floor(Math.random() * 255) + 0)+"."+(Math.floor(Math.random() * 255) + 0);
}
let replace_tag = function (to) {

    config.message.subject = config.message.subject
        .replace("{randomip}", getRandomIp())
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromname = config.message.fromname
        .replace("{randomip}", getRandomIp())
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromemail = config.message.fromemail
        .replace("{randomip}", getRandomIp())
        .replace("{email}", to)
        .replace("{date}", random.date);

}
0 голосов
/ 15 сентября 2018

Я вызываю функцию замены в другой функции, затем вводю ее в цикл

Ах, вот твоя проблема. Ваша функция replace_tag изменит объект config, и после первого вызова он больше не будет содержать тег шаблона, кроме результата замены. Дальнейшие звонки на replace_tag не найдут {randomip} в вашей конфигурации, поэтому новые ips не генерируются.

Вместо этого вы должны поддерживать постоянную конфигурацию (неизменяемую) и создавать новые объекты сообщений каждый раз, когда вам это нужно. Каждый из этих объектов будет иметь разные рандомизированные IP-адреса.

// takes a string, returns a new string
function replace_tags(input, email) {
    return input
    .replace("{randomip}", random.ip)
    .replace("{email}", email)
    .replace("{date}", random.date);
}
// returns a new object, leaves config.message unaltered
function get_customised_message_template(to) {
    return {
        subject: replace_tags(config.message.subject, to),
        fromname: replace_tags(config.message.fromname, to),
        fromemail: replace_tags(config.message.fromemail, to),
    };
}

function kirim(to) {
    const random_message = get_customised_message_template(to);
//  ^^^^^^^^^^^^^^^^^^^^^^
    const message = {
        from: random_message.fromname+'<'+random_message.fromemail+'>',
        to: to,
        subject: random_message.subject,
        text: config.message.text,
        html: html
    };

    transporter.sendMail(message, (error, info) => {
        if (error) console.log(error.response);
        else console.log('Message sent: ', info.accepted);
    });
};
0 голосов
/ 15 сентября 2018

Я думаю, что это будет работать.

random.js:

exports.ip = function() {
    return (Math.floor(Math.random() * 255) + 1)+"."+(Math.floor(Math.random() * 255) + 
        0)+"."+(Math.floor(Math.random() * 255) + 0)+"."+(Math.floor(Math.random() * 255) + 0);
}

send.js:

let replace_tag = function (to) {

    config.message.subject = config.message.subject
        .replace("{randomip}", random.ip())
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromname = config.message.fromname
        .replace("{randomip}", random.ip())
        .replace("{email}", to)
        .replace("{date}", random.date);

    config.message.fromemail = config.message.fromemail
        .replace("{randomip}", random.ip())
        .replace("{email}", to)
        .replace("{date}", random.date);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...