我试图弄清楚如何从xml
文件中获取值并将该值输出到控制台。
const path = require('path');
const fs = require('fs');
const parseString = require('xml2js').parseString;
const sourceFile = path.join(__dirname, 'books.xml');
const document = (sourceFile, callback) => {
fs.readFile(sourceFile, { encoding: 'utf-8' }, function (err, data) {
if (err) {
return err;
}
parseString(data, (err, result) => {
result.catalog.book.forEach(users => {
callback(users.email);
});
});
});
};
console.log(document(sourceFile, data => data));
xml 本身非常简单:
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<email>test@test.com</email>
</book>
</catalog>
但我从函数中得到的是undefined
. 为什么会这样?
更新:我正在尝试将返回值发送到 nodemailer
transporter.sendMail({ from: 'mail@mail.com', to: document(sourceFile, (data) => data), subject: 'Message', text: 'I hope this message gets sent!', }, (err, info) => { if (err) { console.log('error!'); console.log(err.message); } else { console.log('sucess!'); console.log(info.messageId); console.log(info.response); }
但我收到一个错误:'缺少必需的标题'To'。'