2016-01-01 20 views
2

不幸的是我對node.js沒有任何知識,因爲直到現在我使用Ruby和它的REPL叫做Pry。我發現node.js也有這樣的包,可以通過「npm」包管理器來安裝。我這樣做的理由是node.js包「facebook-chat-api」,它對於以編程方式發送Facebook聊天消息很有用,據我所知在Ruby中(或者其他語言也無法實現) 。我安裝在這裏找到https://www.npmjs.com/package/facebook-chat-api包併成功試了一下,有利於實例(face.js和我曾與「節點face.js」運行):如何在匿名函數中應用node.js REPL?

var login = require("facebook-chat-api"); 

login({email: "[email protected]", password: "XXXXXX"}, function(err,api) { 
    if(err) return console.error(err); 
    var yourID = "000000000000000"; 
    var msg = {body: "Hey! My first programmatic message!"}; 
    api.sendMessage(msg, yourID); 
}); 

設置正確的ID爲用戶後它的工作原理和發送信息沒有缺陷。然後,我也安裝了REPL,名爲「locus」(https://www.npmjs.com/package/locus),因爲我想在發送消息後停止node.js腳本,並從REPL命令行發送另一個腳本。所以我的腳本變成以下內容:

var login = require("facebook-chat-api"); 
var locus = require('locus') 

login({email: "[email protected]", password: "XXXXXX"}, function(err,api) { 
    if(err) return console.error(err); 
    var yourID = "000000000000000"; 
    var msg = {body: "Hey! My first programmatic message!"}; 
    api.sendMessage(msg, yourID); 
    eval(locus); 
}); 

不幸的是我的第二個腳本不能按我的預期工作。我真的得到了一個「locus」REPL提示符,但是直到我用命令「quit」退出REPL,纔會發送facebook聊天消息。我希望在發送消息後準確停止我的腳本,我想獲取REPL promt,然後在可能的情況下再次從REPL調用「api.sendMessage」。我該怎麼做,或者我該如何重構我的腳本,使其能夠按照我的理解工作。也許把匿名函數放到一個真正的命名函數中,但我不知道如何正確執行。

+0

你真的需要從命令行調用'api.sendMessage()'嗎?或者你只是想輸入一條信息併發送它? – Shanoor

回答

0

我做了一個小測試,它使用setTimeout作爲異步請求,假髮送請求的同時還處於軌跡中。

這是代碼:

var locus = require('locus'); 

function login() { 
    setTimeout(function() { 
     console.log('message sent'); 
    },2000); 
} 

login(); 

eval(locus); 

這是控制檯與我鍵入一些命令

—————————————————————————————————————————————————————————————————————————— 
3 : function login() { 
4 :  setTimeout(function() { 
5 :   console.log('message sent'); 
6 :  },2000); 
7 : } 
8 : 
9 : login(); 
10 : 
ʆ: message sent // 2 seconds after the repl opened the first message sent 
typeof login 
'function'  // locus is aware of the login function 
ʆ: login(); 
login();   // run the login function 
undefined 
ʆ: message sent // the message was (fake) sent without quitting 
login();   // test a second send 
undefined 
ʆ: message sent // another message was sent. 

如果上面的代碼顯示你所期望的行爲,你的代碼可能。 :

var login = require("facebook-chat-api"); 
var locus = require('locus'); 

login({email: "[email protected]", password: "XXXXXX"}, loginHandler); 

eval(locus); 

function loginHandler (err,api) { 
    if(err) return console.error(err); 
    var yourID = "000000000000000"; 
    var msg = {body: "Hey! My first programmatic message!"}; 
    api.sendMessage(msg, yourID); 
}