2017-01-03 4 views
0

나는 급행 js에있는 상대 URL에 관하여 혼동한다. app.js 및 config.js 내가 "을 my_app"폴더에서 오전 (응용 프로그램 폴더) 및 응용 프로그램을 실행합니다 : 는 I 2 파일이 app.js에서express js - require ('config.js')

:을 my_app 폴더

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' 

입니다? 안쪽에서 시작하지만 명령을 요구하지 않습니다.

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

나 진보주십시오 :

이 내 구조입니다! 감사!

+0

node_modules 폴더가 있습니까? –

+0

물론 있습니다. –

+0

찾을 수 있습니까? –

답변

2

노드, 핵심 모듈 및 사용자 정의 모듈에는 두 가지 유형의 모듈이 있습니다. 작성한 모든 파일은 사용자 정의 모듈입니다. 사용자 정의 모듈을 참조하려면 상대 경로를 전달해야합니다. 그냥 "config.js"를 말한다면

"./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 

는 그것이 node_modules 폴더에 해당 모듈의 핵심 모듈 및 노드 검색을 의미합니다. 파일을 찾지 못하면 상위 디렉토리의 node_modules 폴더에서 파일을 검색합니다. 그래도 모듈을 찾지 못하면 오류가 발생합니다.

경로 모듈을 사용하면 경로를 쉽게 생성 할 수 있으므로 API를 사용하기 쉽고 실수를 피할 수 있습니다. 자세한 정보 here

+0

답장을 보내 주셔서 감사합니다. 하지만이 문제에 대해 더 자세히 설명해 줄 수 있습니까? –

+0

프로젝트의 디렉토리 구조를 제공해 주시겠습니까? –

+0

예, 방금 질문에 추가했습니다. –