2

This is my first javascript file which is called search.js which is used to query through twitter posts.

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. 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.

Here is my index.js file:

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!

1
  • where have you called searchedData function? It should be called inside your app.listen and you should be able to catch the returned value in a variable there. Commented Aug 22, 2018 at 4:21

4 Answers 4

3

Create a promise for the response object and export it.

Your T.get('search/tweets', params, searchedData) is async. So, you can't really export a variable from the scope of searchedData function. You either should import your twit module directly in your main server file. 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:

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

...
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

1

When you want to use any function outside file then use module.export. to make it available.

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

Comments

-3

You have to export the module in your search.js file. 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. 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!
});

2 Comments

This is the first step, but it won't work because the code that populates the response variable is asynchronous.
You're both correct! Edited the post to fully answer him, thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.