2

我试图弄清楚如何从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'。'

4

1 回答 1

1

您不是打印数据的值,而是打印document函数的返回值(不返回任何内容,因此undefined)。

我已经修改了代码,所以现在它可以按你的意愿工作了,

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);
      });
    });
  });
};

document(sourceFile, data => console.log(data));

更新:根据 OP 的评论,

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);
      });
    });
  });
};

document(sourceFile, data => {
  transporter.sendMail({ from: 'mail@mail.com', to: 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);
    }
  });
});
于 2017-04-08T11:44:27.300 回答