2017-01-03 13 views
0

私はexpress jsの相対URLを混乱させます。 私は2ファイルがあります:app.jsとconfig.jsの は、私が "MY_APP" フォルダ(アプリケーションフォルダ)に午前のアプリを実行します。app.jsでexpress js-require( 'config.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フォルダがあるの?内部を開始しても要求コマンドではありません。

これは私の構造体である:

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

は私の進歩を与えてください!ありがとう!

+0

node_modulesフォルダはありますか? –

+0

確かに私は持っています。 –

+0

見つけてもらえますか? –

答えて

2

ノード、コアモジュール、およびユーザ定義モジュールには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

はい、私はちょうど私の質問にそれを追加しました。 –

関連する問題