我的对象在config.js上包含字符串
exports.message = {
fromname : 'admin@bebestorescake.com',
fromemail : 'admin@bebestorescake.com',
subject : 'subjek {randomip} {email} {date}',
text : 'Plaintext version of the message',
letter : 'your-letter.html',
list : 'your-list.txt'
}
在另一个文件中,我需要将{email} {date} {randomip}字符串替换为这样的某些变量或函数返回
{email} replace to email();
{date} replace to date();
{randomip} replace to randomip();
如何在Node.js中实现
答案 0 :(得分:0)
您可以使用模板文字作为快速解决方案:
const replaceTemplate = () => {
const {email, name} = require('./config.js')
return `
${email} this is an email
Hello ${name}
`;
};
const template = 'This is an {email} for {name}';
const obj = {
email: 'hello@world.com',
name: 'John Doe'
};
Object.keys(obj).reduce((prev, curr) => prev.replace(`{${obj[curr]}}`), template)
答案 1 :(得分:0)
我实现此方法的方法是实现一个带有调度表的替换功能:
let { message } = require('config');
function replaceTokens(template) {
const dispatcher = {
email: () => 'somestaticaddress@example.com',
randomip: () => {
const randomInt = () => Math.floor(Math.random() * 256);
return `${randomInt()}.${randomInt()}.${randomInt()}.${randomInt()}`;
},
date: () => (new Date()).toISOString()
};
let output = template;
template.match(/\{[^}]*\}/g)
.map(match => match.substring(1, match.length - 1))
.forEach(token => {
output = output.replace(new RegExp(`{${token}}`,'g'), dispatcher[token]());
});
return output;
}
message.subject = replaceTokens(message.subject);
以上内容将替换主题中令牌的所有个实例。
答案 2 :(得分:0)
您也可以使用以下功能替换config.js中的字符串:
exports.message = {
fromname : 'admin@bebestorescake.com',
fromemail : 'admin@bebestorescake.com',
subject : ({randomip, email, date}) => `subjekt ${randomip || ''} ${email || ''} ${date || ''}`,
text : 'Plaintext version of the message',
letter : 'your-letter.html',
list : 'your-list.txt'
}
然后在需要时传递参数:
message.subject({
email: email(),
date: date()
})