我有以下节点js脚本,它返回作业的持续时间:
var http = require("http");
var fs = require('fs');
var async = require('async');
var readline = require('readline')
//var db = require('./dbPool');
//get file name
var options = {
"method" : "GET",
"hostname" : "127.0.0.1",
"port" : "18080",
"path" : "/api/v1/applications/"
};
exports.getId = function (callback) {
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = JSON.parse(Buffer.concat(chunks));
var arrFound = Object.keys(body).filter(function(key) {
if (body[key].name.indexOf("TeraGen (5MB)") > -1) {
return body[key].name;
}
}).reduce(function(obj, key){
obj = body[key].id;
return obj;
}, {});;
callback(null, arrFound);
});
});
req.end();
}
exports.getId(function(err, id){
//get file name
var options = {
"method" : "GET",
"hostname" : "127.0.0.1",
"port" : "18080",
"path" : "/api/v1/applications/" + id
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = JSON.parse(Buffer.concat(chunks));
var attempts = body.attempts
var arrFound = Object.keys(body).filter(function(key) {
return attempts[0].duration;
}).reduce(function(obj, key){
obj = body.attempts[0].duration;
return obj;
}, {});
//console.log(arrFound);
callback(null, arrFound);
});
});
req.end();
});
当我运行它时会抛出以下错误:
$ node getEventLog.js 815963 /modules/getEventLog.js:73 callback(null,arrFound); ^
ReferenceError:未定义回调 在IncomingMessage。 (/modules/getEventLog.js:73:13) 在emitNone(events.js:111:20) 在IncomingMessage.emit(events.js:208:7) at endReadableNT(_stream_readable.js:1056:12) at _combinedTickCallback(internal / process / next_tick.js:138:11) at process._tickCallback(internal / process / next_tick.js:180:9)
我有一种感觉,我需要创建一个函数,所以我尝试了:
exports.getDuration = function (callback) {
exports.getId(function(err, id){
//get file name
var options = {
"method" : "GET",
"hostname" : "127.0.0.1",
"port" : "18080",
"path" : "/api/v1/applications/" + id
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = JSON.parse(Buffer.concat(chunks));
var attempts = body.attempts
var arrFound = Object.keys(body).filter(function(key) {
return attempts[0].duration;
}).reduce(function(obj, key){
obj = body.attempts[0].duration;
return obj;
}, {});
console.log(arrFound);
callback(null, arrFound);
});
});
req.end();
})
};
它似乎不起作用。我哪里错了?
答案 0 :(得分:1)
你的第二个例子应该有用,你只需要调用它
exports.getDuration(function(err, duration){
if(err) return console.log(err)
console.log(duration)
}
您的第一个示例无效,因为您尝试回调数据但未指定回调。如果您不想创建第二个示例中的其他函数,只需删除回调并使用持续时间数据执行您需要的任何操作
//console.log(arrFound);
callback(null, arrFound); //remove this
//arrFound should be the duration, so do whatever you need with it here