반응형
다른 파일에 있는 것을 가져다 쓸려면 어떻게 해야할까?
https://jjaong34.tistory.com/50
[node.js] process, file system(fs)
https://nodejs.org/docs/latest-v19.x/api/ Index | Node.js v19.9.0 Documentationnodejs.org노드 문서 node 에 진입 후 process를 입력하면 버전과 정보에 대해서 나온다. 그 중에 argv 라는 것을 알아보자 process.argv 를 콘솔
jjaong34.tistory.com
저번시간에 node에서 fs와 process를 써봤는데
const fs = require('fs')
fs는 내부 모듈이기 때문에 바로 사용이 가능했다.
외부 모듈을 가져올때
예를 들면 create라는 모듈을 가져온다
const create = require('create')
console.log(create);
찾을 수 없다고 나온다
내부 모듈이 아니기 때문이다
해당파일 경로에서 같은파일에 있다면
./를 추가해야한다.
create.js
const add = (a, b) => {return a+b;}
const PI = 3.14;
를 ./create로 불러오면
const create = require('./create')
console.log(create);
결과는
빈객체가 불러와진다.
그렇다면 create.js를 가져오고 싶으면 어떻게 해야할까?
module.exports를 해줘야한다.
const add = (a, b) => {return a+b;}
const PI = 3.14;
module.exports.add = add;
module.exports.PI = PI;
이런식으로 해당 함수나 상수, 변수를 내보내주면
받아서 활용이 가능하다.
잘 받아와졌는지 확인해보면
잘 불러와진다.
원하는 요소만 가져오고 싶다면
const create = require('./create')
console.log(create.PI);
이런식으로 쓸 수 있고
const {PI, add} = require('./create')
console.log(PI);
이렇게도 가능하다
둘다 결과는 같다
반응형
'nodejs' 카테고리의 다른 글
[node.js] express 시작 (0) | 2023.05.03 |
---|---|
[node.js] install, init, node_modules, package.json (0) | 2023.05.01 |
[node.js] process, file system(fs) (0) | 2023.04.22 |
[node.js] 설치, REPL, 파일 실행 (0) | 2023.04.21 |
터미널 명령 (0) | 2023.04.20 |