2016-12-05 119 views
-3

我正在處理一個運行node.js的JS項目,我無法弄清楚如何讓提示正常工作以便用戶輸入。我從npm安裝了它,然後執行這些步驟,我可以讓程序提示用戶輸入,但是我無法將結果存儲在變量中。使用node.js的提示用戶輸入?

我想要的是提示用戶每輪轉動一次(上,下,左或右)並使用結果。我試圖讓一個全局的移動變量並影響它在提示部分,但它似乎並沒有工作。

var Moving = function(maxMoves){ 

    for(var n=maxMoves; n>0;){ 
     var move; 
     var l; 
     //This would prompt for a direction (up,down,left,right) 
     move = prompt(); 
     //And this would prompt for the number of tiles to advance; 
     l = prompt(); 
     Direction(move,l); 
     n-=l; 
    } 
}; 
+3

我們不能幫你看看我們看不到的代碼。將問題簡化爲[mcve],並將其放在問題中。 –

+0

基本上,與我的代碼無關,我的問題很簡單:如何將用戶輸入存儲在node.js中的變量中? – Dat8StringGuy

+1

複製[*如何從node.js中的用戶獲取控制檯輸入?](http://stackoverflow.com/questions/26683734/how-can-i-take-console-input-from-a-用戶在節點js)請[在發佈之前搜索。](/ search?q =如何+存儲+ a + user + input + in + a + variable + in + node.js)更多關於搜索[here ](/幫助/搜索)。 –

回答

1

當你說「從故宮安裝了」我假設你從烙鐵指prompt模塊。

從自己的文件,與大多數節點的東西,它看起來像它暴露了一個異步函數,所以你會處理的提示回調裏面輸入:

var prompt = require('prompt'); 

    // 
    // Start the prompt 
    // 
    prompt.start(); 

    // 
    // Get two properties from the user: username and email 
    // 
    prompt.get(['username', 'email'], function (err, result) { 
    // 
    // Log the results. 
    // 
    console.log('Command-line input received:'); 
    console.log(' username: ' + result.username); 
    console.log(' email: ' + result.email); 
    }); 

將其存儲在一個變量會有不同比從上面的結果對象訪問它,但意識到,因爲它是異步的,它只會在回調中可靠。

+0

我還是有點困惑。考慮到它是異步的,我不知道如何將它存儲在我可以立即使用的變量中。我嘗試使用該模板並添加_move = result; _,但是當我嘗試_console.log(移動)_時,我得到了_undefined_。 – Dat8StringGuy

+0

正如我所說的,變量只能在提示回調中可靠地使用。同樣,如果您發佈代碼,我們可以更輕鬆地幫助您提供具體建議。 – Paul

+0

爲該問題添加了代碼示例。 – Dat8StringGuy