我有两个js文件screenshot.js和main.js,我想从screenshot.js返回JSON到main.js,但是它没有返回结果,在screenshot.js中当你运行console.log(this.result)文件时,你会在控制台中看到结果,但是当你在main.js文件中调用它时结果为空,那么如何解决这个问题。如何调用NodeJS内部的模块函数createServer
这是我的代码。
screenshot.js
module.exports={
result: '',
run: function(url,w,h){
var phantom=require('phantom');
phantom.create().then(function(ph){
ph.createPage().then(function(page){
page.property('viewportSize',{width:w,height:h}).then(function(){
page.open('http://' + url + '/').then(function(status){
page.property('onLoadFinished').then(function(){
console.log(status);
if (!(status == 'success')){
this.result={'image':'no'};
this.result=JSON.stringify(this.result);
// console.log(this.result);
page.close();
} else {
this.result=page.renderBase64('jpeg').then(function(img){
this.result={'image': img};
this.result = JSON.stringify(this.result);
// console.log(this.result);
page.close();
});
}
});
});
});
});
});
return this;
},
get: function(){
return this.result;
}
}
main.js
var http = require('http');
var parsing = require('url');
var screenshot = require('./screenshot');
http.createServer(function(req, res) {
var url, img, w, h, query_object, result;
url = req.url;
url = url.replace('/', '');
url = url.trim();
if (!(url == 'favicon.ico')) {
console.log(url);
query_object = parsing.parse(req.url, true).query;
console.log(query_object);
res.writeHeader(200, { "Content-Type": "text/html" });
w = parseInt(query_object.width);
h = parseInt(query_object.height);
result = screenshot.run(url, w, h).get();
console.log(result);
res.end();
}
}).listen(80, '127.0.0.1');
console.log('server isn running....');