2017-01-03 177 views
0

我在express js中混淆了相對url。 我有2個文件:app.js和config.js 我在 「程序my_app」 文件夾(應用程序文件夾),並運行應用程序:express js - require('config.js')

在app.js:

var config = require('config.js'); 
// => throw err : Cannot find module 'config.js' 

var config = require('/config.js'); 
// => throw err : Cannot find module '/config.js' 

var config = require('./config.js'); 
// => throw err : Cannot find module 'http://localhost:3000/config.js' 

var config = require(__dirname + '/config.js'); 
// => throw err : Cannot find module 'http://localhost:3000/config.js' 

哪裏是my_app應用文件夾?它不在require命令中,但是從裏面開始。

這是我的結構:

start 
    -- controllers 
    -- models 
    -- node_modules 
    -- public 
    -- views 
    app.js 
    config.js 
    package.json 
    router.js 

請給我前進!謝謝!

+0

你有一個node_modules文件夾嗎? –

+0

當然,我有。 –

+0

你可以嘗試在那裏找到它嗎? –

回答

2

節點中有兩種類型的模塊,核心模塊和用戶定義的模塊。 您編寫的每個文件都是用戶定義的模塊。要引用任何用戶定義的模塊,您需要傳遞相對路徑。

"./config.js" - here ./ means that config file is in the current directory (of the file you are working on) 
"../config.js" - here ../ means that config file is in the parent directory (of the file you are working on) 
__dirname - macro which gives the path of the directory of the file you are working on 
__filename - macro which gives the path of the file that you are working on 

,如果你只是說「config.js」這意味着它是一個核心模塊和節點搜索在node_modules文件夾模塊。如果在那裏找不到它,它會在父目錄的node_modules文件夾中搜索該文件,依此類推。如果它仍然沒有找到模塊,它會拋出一個錯誤

最好使用路徑模塊來構建路徑,因爲它有一些易於使用的API,它可以避免錯誤。 更多信息here

+0

感謝您的回覆!但是,您可以提供更多有關此問題的詳細信息嗎? –

+0

你能否提供你的項目的目錄結構? –

+0

是的,我剛剛添加到我的問題。 –