Node.js无法访问另一个JavaScript文件中的变量

时间:2018-08-22 04:00:43

标签: javascript node.js

这是我的第一个javascript文件,称为search.js,用于通过Twitter帖子进行查询。

Option Explicit

Private mAllTheResults As Collection_T

Public Sub RunMe()
    Dim mode As String
    Dim goodObject As ResultLine
    Dim wrongObject As Range
    Dim i As Long
    Dim result1 As String
    Dim result2 As String

    Set mAllTheResults = New Collection_T
    Set mAllTheResults.TestObject = New ResultLine


    'Add a correct type.
    Set goodObject = New ResultLine
    With goodObject
        .VariableThing1 = "a"
        .VariableThing2 = "b"
    End With
    mAllTheResults.AddObject goodObject, "yep"

    'Add an incorrect type.
    Set wrongObject = Sheet1.Range("A1")
    mAllTheResults.AddObject wrongObject, "nope"

    'Retrieve an item
    Set goodObject = mAllTheResults.GetObjectIfExists("yep")
    If Not goodObject Is Nothing Then
        With goodObject
            .VariableThing1 = "c"
            .VariableThing2 = "d"
        End With
    End If

    'Demonstrate the collection has retained the property change.
    MsgBox "VariableThing1 = " & mAllTheResults.GetObjectIfExists("yep").VariableThing1

End Sub

twitter帖子存储在最后一个函数中返回的“ response”变量中。当我打印响应变量时,它会正确打印帖子。我需要在运行服务器的index.js中访问该变量。

这是我的index.js文件:

var Twit = require('twit');
var config = require('./config') 

var T = new Twit(config); 

var params = {

   q: '#stackOverflow',

   count: 1

} 


var response = null; 

T.get('search/tweets', params, searchedData); 


function searchedData(err, data, response) {
   response = data
   console.log(response) //prints the post
   return response;

} 

有人可以帮助我吗?我尝试过在线查找,但仍然无法拼凑。

谢谢!

4 个答案:

答案 0 :(得分:2)

  

为响应对象创建承诺并导出。

您的T.get('search/tweets', params, searchedData)是异步的。因此,您实际上无法从searchedData函数的作用域导出变量。您要么应该直接在主服务器文件中导入 twit 模块。或者,您可以创建一个承诺,您可以先导出然后再导入主文件。以下是如何使用Promise做到这一点:

var Twit = require('twit');
var config = require('./config') 

var T = new Twit(config); 

var params = {
   q: '#stackOverflow',
   count: 1
} 

var postPromise = new Promise((resolve, reject) => {
     T.get('search/tweets', params, (err, data) => {
         if (err) {
              reject(err);
         } else {
            resolve(data)
         }
     }); 
});

module.export.postPromise = postPromise;

然后您可以将这个承诺导入您的 index.js 文件中,然后执行以下操作:

const getPosts = require('./search.js').postPromise;
const express = require('express');

const app = express();

app.get('/posts', function(req, res) {
      getPosts.then(posts => res.status(200).json(posts));
})

...

答案 1 :(得分:1)

module.exports.getTweets = function(callback) {
    var Twit = require('twit');
    var config = require('./config')

    var T = new Twit(config);

    var params = {

        q: '#stackOverflow',

        count: 1

    }

    T.get('search/tweets', params, callback);
}

您应该使用回调链接正确获取推文。

const mySearch = require('./search.js');
const express = require('express');

const app = express();

app.get('/', function(req, res) {
    res.send('Hello World');
})

app.listen(3000, function() {
    console.log("Server started on port 3000...");
    //console.log(mySearch.response)//prints 'undefined'

    mySearch.getTweets(function(err, data, response) {
        console.log(data)
    });
})

答案 2 :(得分:1)

如果要使用文件外的任何功能,请使用 module.export 。 使其可用。

  

Search.js

var Twit = require('twit');
var config = require('./config')

var T = new Twit(config);

var getTweet = function (params, callback) {
    T.get('search/tweets', params, function (err, data, response) {
        if (error) {
            console.log(error);
            callback(error,null);
        } else {
            callback(null,data);
        }
    });
}

module.exports.getTweet = getTweet;
  

index.js

const mySearch = require('./search.js');
const express = require('express');

const app = express();

app.get('/', function(req, res) {
    res.send('Hello World');
})

app.listen(3000, function(){
    console.log("Server started on port 3000...");
    var params = {
        q: '#stackOverflow',
        count: 1
     } 

    mySearch.getTweet(params,function(error,response){
        error ? console.log(error) : console.log(response);
    });
});

答案 3 :(得分:-3)

您必须将模块导出到search.js文件中。这样做的代码如下:

module.exports = {
  response: response
};

但是,正如注释中所述,对于功能完整的模块,您需要导出Promise,例如,假设从twitter提取数据是异步操作。为此,创建一个像这样的函数:

module.exports = {
  function getData() {
    return new Promise(function (resolve, reject) {
      var response = null; 

      T.get('search/tweets', params, function (err, data, response) {
        if (err) {
          reject(err);
        }
        else {
          response = data
          console.log(response) // prints the post
          resolve(response);
        }
      }); 
    });
  }
}

您可以让他们这样做来访问检索到的推文:

mySearch.getData().then(function (response) {
  console.log(response); // Data retrieved
}).catch(function (error) {
  console.log(error); // Error!
});