我对node.js相当陌生,我的起点是app.js
,它调用一个名为的文件xmlParser.js
,该文件使用xml2js
节点模块解析输入的xml文件。这是什么app.js
样子,
//include the modules
var express = require('express'),
app = express(),
ejs = require('ejs'),
xmlParser = require('./utils/xmlParser.js');
//save the pain of writing .ejs after each render
app.set("view engine","ejs");
//these will hold the result of the function in the file xmlParser
var listJSON, logJSON = {};
app.get('/portfolio', function(req, res, next){
//call parse function in file xmlParser.js
xmlParser.parse(__dirname + "/xml/svn_log.xml", listJSON);
xmlParser.parse(__dirname + "/xml/svn_list.xml", logJSON);
console.log("middleware was excuted!");
next();
}, function(req, res){
console.log(listJSON);
});
现在这是文件的xmlParser.js
样子,
//include the modules
var fs = require('fs'),
xml2js = require('xml2js'),
parser = new xml2js.Parser();
//this function parse xml file with name as filename to json and stores it in variable outputJSON
function parse(filename, outputJSON){
fs.readFile(filename, function(err, data){
if(err){
console.log('cannot read file.');
} else {
parser.parseString(data, function(err, result){
if(err) console.log('cannot parse file.');
else {
outputJSON = result;
}
});
}
});
}
module.exports = {
parse
}
现在,当我运行该应用程序并转到路由时,/portfolio
我希望将其打印出来:
middleware was executed!
[object]
但这就是我在节点控制台上得到的,
middleware was executed!
undefined
现在,我想要的功能是xmlParser.js
执行并将解析的JSON对象存储在listJSON
传递给它的对象中。当我listJSON
作为parse()
函数的第二个参数传递时,它是否通过引用传递?为什么我得到“ undefined printed when my function in the file
xmlParser.js”在其中存储对象?
一个问题是,你的parse
函数调用fs.readFile
和parser.parseString
它们是异步的。第二个问题是您在函数中更改了对象:JavaScript通过对象共享传递参数。含义:原始变量按值传递:更改参数不会更改源变量。非原始变量(如对象和数组)也不能更改,但它们的属性也可以更改。
虽然确实在调用parse
之前先调用next
,但是异步读取文件,然后异步解析(而不阻塞您的路由代码),这next
要比程序完成解析文件的时间来得早。
您可以做的是一步一步地传递异步操作,并使解析返回结果,然后进行设置。首先将您的parse
函数更改为接受回调并调用它:
function parse(filename, callback){
fs.readFile(filename, function(err, data){
if(err){
console.log('cannot read file.');
return callback(err);
} else {
parser.parseString(data, function(err, result){
if(err) {
console.log('cannot parse file.');
return callback(err);
}
else {
return callback(null, result);
}
});
}
});
}
然后,将解析函数与函数一起传递next
:
app.get('/portfolio', function(req, res, next){
xmlParser.parse(__dirname + "/xml/svn_log.xml", function(err, list) {
listJSON = list;
xmlParser.parse(__dirname + "/xml/svn_list.xml", function(err, log) {
logJSON = log;
next();
});
});
console.log("middleware was excuted!");
}, function(req, res){
console.log(listJSON);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句