简体   繁体   English

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

[英]Node.js Can't access variable in another javascript file

This is my first javascript file which is called search.js which is used to query through twitter posts.这是我的第一个 javascript 文件,名为 search.js,用于通过 twitter 帖子进行查询。

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;

} 

The twitter posts are stored in the 'response' variable returned in the last function. Twitter 帖子存储在最后一个函数中返回的“响应”变量中。 When I print the response variable, it properly prints the post.当我打印响应变量时,它会正确打印帖子。 I need to access that variable in my index.js which runs the server.我需要在运行服务器的 index.js 中访问该变量。

Here is my index.js file:这是我的 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...");
    console.log(mySearch.response)//prints 'undefined'
})

Can anyone please help me?谁能帮帮我吗? I tried looking online but I still can't put the pieces together.我尝试在网上查找,但我仍然无法将这些碎片拼凑在一起。

Thanks!谢谢!

Create a promise for the response object and export it.为响应对象创建一个承诺并将其导出。

Your T.get('search/tweets', params, searchedData) is async.你的T.get('search/tweets', params, searchedData)是异步的。 So, you can't really export a variable from the scope of searchedData function.因此,您不能真正从searchedData函数的范围中导出变量。 You either should import your twit module directly in your main server file.您应该直接在主服务器文件中导入twit模块。 Or, you can create a promise that you can export and then import in the main file.或者,您可以创建一个可以导出然后导入主文件的承诺。 Below is how you can do it using promises:以下是您如何使用承诺来做到这一点:

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;

And then you can import this promise in your index.js file and do something like:然后你可以在你的index.js文件中导入这个 promise 并执行如下操作:

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));
})

...
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);
}

You should use callback chaining to get the tweets properly.您应该使用回调链来正确获取推文。

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)
    });
})

When you want to use any function outside file then use module.export .当您想使用文件外的任何函数时,请使用module.export to make it available.使其可用。

Search.js搜索.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索引.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);
    });
});

You have to export the module in your search.js file.您必须在search.js文件中导出模块。 The code to do so looks like this:这样做的代码如下所示:

module.exports = {
  response: response
};

but, as stated in the comments, for a fully functional module you need to export a Promise, for example, given that fetching data from twitter is an asynchronous operation.但是,正如评论中所述,对于一个功能齐全的模块,您需要导出一个 Promise,例如,假设从 twitter 获取数据是一个异步操作。 To do so, create a function like this:为此,请创建如下函数:

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);
        }
      }); 
    });
  }
}

You can them access the retrieved tweets doing this:您可以通过以下方式访问检索到的推文:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将变量从 javascript 文件传输到 node.js 中的另一个 html 文件? - How can I transfer a variable from a javascript file to another html file in node.js? 如何在我的node.js控制台中的javascript文件中声明一个变量? - How can I access a variable declared in a javascript file in my node.js console? 无法访问自定义Node.js模块中的变量 - Can't access variable in custom Node.js module 为什么我不能在Node.js中将另一个文件中的导出变量设置为另一个文件? - Why can't I set an exported variable in one file from another in Node.js? 无法使用Node.js通过HTML访问JavaScript静态文件 - Can't access JavaScript static file through HTML using Node.js 无法通过node.js运行javascript文件 - Can't run a javascript file through node.js 文档未在 node.js 上定义 - 如何将另一个 .js 文件中的变量导入 node.js 服务器? - Document is not defined on node.js - How can i import a variable from another .js file to node.js server? 无法正确访问NODE_ENV环境变量,这是node.js的错误吗? - Can't access the NODE_ENV environment variable properly, is this a bug with node.js? 通过导出(Node.js)访问HTML文件中的JS变量 - Access JS variable in HTML file via export (Node.js) Node.js从另一个函数访问变量的值 - Node.js access the value of variable from another function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM