2017-01-09 83 views
0

使用Node.js,我將一個工作片段分成兩個片段,產生相同的結果。工作片段有一個require語句,位於根目錄中。拆分的兩段在根目錄的第一階段工作,但第二階段失敗並報告無法找到eTrade庫。這是要求聲明。需要路徑在根中工作,但不在其他地方工作

var etrade = require('./lib/etrade'); 

當從server.js根,一切正常,但是在拆分項目執行,捕捉變量現在出現在路由文件夾index.js並不起作用。客戶端報告無法找到eTrade庫。這裏有一些我不瞭解的,可能是關於如何解決require中的路徑規範。

與此同時,我使用一個全局變量工作,我從根目錄中的app.js傳遞到routes文件夾中的index.js。我可以通過這種方式繼續發展,但如果我瞭解如何進行第一個變體工作,情況會好得多。

請編輯問題並顯示您的文件層次結構,然後向我們展示如何合併文件?您使用的工具以及輸出的位置

server.js在根中運行並且工作得很好。 app.js在根中運行並且是合併系統的一部分,並且可以工作。 index.js在root/routes文件夾中運行,並且是合併系統的B部分,並且失敗。 root/lib/eTrade包含eTrade模塊。

工作片段(server.js)在eTrade網站上打開一個確認窗口,用戶複製/粘貼一個確認代碼,該代碼被回送到服務器端的控制檯。失敗的片段(它是A和B的組合)拒絕將變量(確認碼)傳遞給B,並且因爲它報告找不到eTrade庫,所以我認爲問題在於require語句中的路徑,它是

var etrade = require('./ lib/etrade');

合併的系統執行任務的第一部分,但不會將變量傳遞給任務的第二部分,我認爲這是因爲B中的變量超出範圍。

下面是工作段:

/* 
* Module dependencies 
*/ 
const port = 3000 

var express = require('express') 
    , stylus = require('stylus') 
    , nib = require('nib') 
    , logger = require('morgan') 
    , routes = require('./routes/index') 
    , users = require('./routes/users') 
    ,app = express() 

function compile(str, path) { 
    return stylus(str) 
    .set('filename', path) 
    .use(nib()); 
} 

app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 

//app.use('/', routes); 
//app.use('/users', users); 
app.use(logger('dev')); 
app.use(stylus.middleware(
    { src: __dirname + '/public' 
    , compile: compile 
    } 
)); 
app.use(express.static(__dirname + '/public')) 

//from expressSite 
// from readme 
var etrade = require('./lib/etrade'); 

var configuration = 
{ 
    useSandbox : true, // true if not provided 
    key : '', //actual value deleted 
    secret : '' //actual value deleted 
} 

var et = new etrade(configuration); 
    //here we send the user a credentials link 
et.getRequestToken(
    function(authorizationUrl) { 
    // Your service requires users, who will need to visit 
    // the following URL and, after logging in and 
    // authorizing your service to access their account 
    // data, paste the E*TRADE provided verification 
    // code back into your application. 
     app.get('/', function (req, res) { 
     res.render('AuthApp', 
     { authLink : authorizationUrl } 
    ) 
     }); 

    console.log("AuthorizationURL " + authorizationUrl + " "); }, 

    function(error) { 
     console.log("Error encountered while attempting " + 
       "to retrieve a request token: " + 
       error); 
    } 
); //end getRequestToken 

//user sends confirmation code and we get acesss token 
app.get('/users/sendcode', function (req, res) { 
    console.log('verification code is '+req.query.vCode); 
//end get verification code 
    et.getAccessToken(req.query.vCode, 
     function() { 
     // Your app can start using other E*TRADE API now 
     // begin main interaction 
     // this is where we should land first after oath 
     // hand it over to the db page? 

     //et.listAccounts(); 
     //console.log(a); 
     res.render('ETQuery'); 
     console.log('thread entered getAccessToken function') 
     // console.log(AccessToken) 
     }, 

     function(error) { 
     console.log("Error encountered while attempting " + 
        "to exchange request token for access token: " + 
        error); 
     } 
    ); 
}) 

app.listen(port, (err) => { 
    if (err) { 
    return console.log('something bad happened', err) 
    } 

    console.log(`CIA is listening to the FSB on ${port}`) 
}) 

下面是新部在根app.js A碼。你可以看到我是如何修補它以使用全局的。

var etrade = require('./lib/etrade'); 

var configuration = 
{ 
    useSandbox : true, // true if not provided 
    key : '', //actual value deleted 
    secret : '' //actual value deleted 
} 

var et = new etrade(configuration); 
// here we send the user a credentials link 
et.getRequestToken(
    function(authorizationUrl) { 
    // Your service requires users, who will need to visit 
    // the following URL and, after logging in and 
    // authorizing your service to access their account 
    // data, paste the E*TRADE provided verification 
    // code back into your application. 
    // app.get('/', function (req, res) { 
    // res.render('index', 
    //  { authLink : authorizationUrl } 
    // ) 
    // }); 

    console.log("AuthorizationURL is " + authorizationUrl + " "); 
    global.ETauthUrl = authorizationUrl; 
}, 

    function(error) { 
     console.log("Error encountered while attempting " + 
       "to retrieve a request token: " + 
       error); 
    } 
); //end getRequestToken 

但是B部分沒有捕獲到令牌。這裏奇怪的是,報告失敗是爲了找到eTrade庫,而該庫在B中沒有被引用。在工作片段中,我無法將令牌傳遞到server.js之外,但是我可以在服務器端報告它用戶粘貼並點擊客戶端的發送按鈕後。這裏是B.

var router = express.Router(); 

/* GET home page. */ 
router.get('/', function(req, res) { 
    res.render('index', 
     { authLink : ETauthUrl } 
    ) 
}); 

這隻適用於全局變量。

+0

我們可以有一些代碼嗎? –

+0

請編輯問題並顯示您的文件層次結構,然後向我們展示如何合併文件?你使用了哪些工具,以及輸出的位置 –

回答

0

./...通知NodeJS從當前目錄加載適用的代碼。這將在應用程序的根目錄下工作於server.js。但是,要正確引用另一個目錄中的文件,您需要正確引用它的路徑。

E.g.給出

bootstrap/ 
├── lib/ 
│ ├── etrade.js 
├── modules/ 
│ ├── foo.js 
| ├── bar/ 
|  ├── bar.js 
└── server.js 

你需要在server.js引用etrade爲:

var etrade = require('./lib/etrade'); 

而且在modules/foo.js爲:

var etrade = require('../lib/etrade'); 

而且在modules/bar/bar.js爲:

var etrade = require('../../lib/etrade'); 

More on how NodeJS require resolves files

 
require(X) from module at path Y 
1. If X is a core module, a. return the core module b. STOP 
2. If X begins with './' or '/' or '../' a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) 
3. LOAD_NODE_MODULES(X, dirname(Y)) 
4. THROW "not found" 

LOAD_AS_FILE(X) 
1. If X is a file, load X as JavaScript text. STOP 
2. If X.js is a file, load X.js as JavaScript text. STOP 
3. If X.json is a file, parse X.json to a JavaScript Object. STOP 
4. If X.node is a file, load X.node as binary addon. STOP 

LOAD_AS_DIRECTORY(X) 
1. If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. let M = X + (json main field) c. LOAD_AS_FILE(M) 
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP 
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 
4. If X/index.node is a file, load X/index.node as binary addon. STOP 

LOAD_NODE_MODULES(X, START) 
1. let DIRS=NODE_MODULES_PATHS(START) 
2. for each DIR in DIRS: a. LOAD_AS_FILE(DIR/X) b. LOAD_AS_DIRECTORY(DIR/X) 

NODE_MODULES_PATHS(START) 
1. let PARTS = path split(START) 
2. let I = count of PARTS - 1 
3. let DIRS = [] 
4. while I >= 0, a. if PARTS[I] = "node_modules" CONTINUE b. DIR = path join(PARTS[0 .. I] + "node_modules") c. DIRS = DIRS + DIR d. let I = I - 1 
5. return DIRS 
相關問題