簡體   English   中英

Node.js命令行中的調用函數

[英]Call function in Node.js command line

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

我正在嘗試在Node.js中運行功能getTweets() 我本質上想運行類似: “ node app get-tweets”並讓其調用getTweets()並在終端中將結果返回給我。 我知道我可以在最后調用該函數並運行node app ,但是我想在同一模塊中添加其他函數,如postTweet()

一種方法是使用process.argv

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

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

var functionToCall = process.argv[2];

functionToCall && functionToCall();

您可以通過node app.js getTweets執行它

argv中的前兩項將是節點可執行文件和要執行的文件的路徑,然后是傳遞給應用程序的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM