[英]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.