2
require("dotenv").config();
const Twitter = require("twitter");
const keys = require("./keys");
const T = new Twitter(keys.twitter);    

let params = {
screen_name: "TWITTER_NAME",
count: 20
}

function getTweets() {
T.get("statuses/user_timeline", params, gotTweets);
}

function gotTweets(error, data, response) {
if (error) {
    console.log("ERROR: " + error);
} else {
    let tweetLength = data.length;
    for (i = 0; i < tweetLength; i++) {
        console.log(JSON.stringify(data[i].text + " --- POSTED ON: " + 
data[i].created_at, null, 2))
    }
}
}

I am trying to run the function getTweets() in Node.js. I want to essentially run something like: "node app get-tweets" and have it call getTweets() and return the results to me in the terminal. I understand I could just call the function at the end and run node app, but I want to add other functions in the same module like postTweet().

1 Answer 1

3

One way to do it is by using process.argv

function getTweets() {
    console.log('getTweets called');
}

function postTweets() {
    console.log('postTweets called')
}

var functionToCall = process.argv[2];

functionToCall && functionToCall();

You can execute it by node app.js getTweets

The first 2 items in argv will be the path to your node executable and the file you are executing followed by arguments you passed to your app.

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

2 Comments

Can I export the function into another .js file and call it like: node app.js get-tweet.js ?
Yes, but if it's in another file you might as well just execute that file.

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.