【发布时间】:2018-01-02 03:34:14
【问题描述】:
我正在 Node 中构建一个服务器,它将搜索文件夹以查看是否存在 XML 文件 (glob),如果存在,则将 (fs) 中的文件作为 JSON 对象 (xml2js) 读取并最终存储它在某处的数据库中。我想将解析器的结果输出到另一个变量中,这样我就可以对数据做其他事情了。据我所知,有些东西正在同步运行,但我不知道如何停止它并让我等到它完成才能继续前进。
我将我的函数从 app.js 中分离到其他地方的控制器中:
app.controller.js
const fs = require('fs-extra');
const glob = require('glob');
const xml2js = require('xml2js');
exports.requests = {};
exports.checkFileDrop = async () => {
console.log('Checking for xml in filedrop...');
// this is the only place await works...
await glob('./filedrop/ALLREQUESTS-*.xml', (err, files) => {
var parser = new xml2js.Parser();
// this is looking for a specific file now, which I'll address later once I can figure out this issue
fs.readFile('./filedrop/ALLREQUESTS-20170707.xml', 'utf16le', function (err, data) {
if (err) {
console.log('ERROR: ', err);
} else {
parser.parseString(data, (err, result) => {
if (err) {
console.log('ERROR: ', err);
} else {
console.log('data found');
exports.requests = JSON.stringify(result.Records.Record);
// data is outputted here correctly
console.log(exports.requests);
// this doesn't even seem to want to save to exports.requests anyways...
}
});
}
});
});
}
app.js
const appController = require('./controllers/app.controller');
// check if there is file in filedrop
appController.checkFileDrop();
// prints out an empty object
console.log(appController.requests);
// can't do anything if it doesn't exist yet
appController.saveToDB(appController.requests);
【问题讨论】:
标签: javascript node.js ecmascript-6 fs xml2js