无法在函数express js / request js中导出变量

时间:2015-04-09 07:58:05

标签: javascript node.js express

我的导出代码

//export.js    
var express = require('express'),
    fs      = require('fs'),
    request = require('request'),
    cheerio = require('cheerio'),
    app     = express();

    var episode = [],
        title = [],
        synopsis = [],
        reviews = [],
        date = [];

exports.showGrab = function(url,response){
    request(url,response, function(error, response, html){

       var $ = cheerio.load(html),
            shows = {bitten:['http://www.tv.com/shows/bitten-2013/episodes/']};
        $('.no_toggle._clearfix').eq(1).filter(function(){
            var data = $(this);
                episode = data.children().first().children().last().text();
                exports.episode = episode;
        })
    })
}
console.log(episode); // => defined as [] not the value given in the function 

//import.js
var express = require('express'),
    fs      = require('fs'),
    request = require('request'),
    cheerio = require('cheerio'),
    app     = express(),
    server  = require('./export');


console.log(server.episode);
server.showGrab('http://www.tv.com/shows/bitten-2013/episodes/');
使用函数server.showGrab在导入脚本中的

工作正常但我需要访问导入脚本中show grab函数中的变量。我相信这个问题可以归结为一个范围问题,如果我在一个函数之外导出变量它们工作正常,但我的印象是,按照我的方式声明变量会使它们成为全局变量。如何在导入脚本中运行此功能,同时仍然传递一个网址并返回episode进行处理?

1 个答案:

答案 0 :(得分:0)

@Pointy你是对的,导入脚本在定义之前调用了值

//import.js
if (server.episode === undefined){
var test = setInterval(function(){
        if (server.episode != undefined){
            clearInterval(test);
        }
        console.log(server.episode);
    }, 1000);
}

这就是诀窍,因为某些原因使用else而不是将if包装在if中不起作用。