나의 발자취

node.js 파일 간 함수 전달 (module.exports), 파일 읽고 쓰기 본문

Backend

node.js 파일 간 함수 전달 (module.exports), 파일 읽고 쓰기

달모드 2024. 9. 25. 10:12
const add = (a, b) => a + b;

module.exports = add; // module.export로 원하는 함수를 내보내기


module.exports로 add 함수를 내보낸다.

 

 

또 다른 파일에서, 사용하고 싶은 함수가 위치한 곳을 require()를 통해 가져와 변수에 할당하고, 사용할 수 있다.

 

const add = require('./ch03_01'); // require 함수로 함수 받기
console.log(add(2, 3));

 

 

두 개의 함수를 export하고 싶다면?

ch03_01.js

const add = (a, b) => a + b;
function subtract(a, b) {
return a - b;
}

module.exports.subtract = subtract;
module.exports.add = add;

 

ch03_02.js

const calc = require('./ch03_01'); // require 함수로 함수 받기
console.log(calc.add(2, 3));

const subtract = require("./ch03_01");
console.log(calc.subtract(5,1));

 

 

파일 읽고 쓰기

 

 

커멘드 명령어로 recursive directory 생성

mkdir -p [만들 디렉토리 경로]

 

특정 경로에 파일 생성

const fs = require('fs');
const dirname = 'naver/daum/google';
fs.mkdirSync(dirname, { recursive: true });

// fs.writeFileSync 를 이용하여 naver/daum/google/out.txt 만들어보세요

const content = "안녕하세요 홍길동입니다 \n반갑습니다";
fs.writeFileSync(`${dirname}+/out.txt`, content);

 

 

커멘드 명령어로 .txt 파일 모두 지우기

find . -name "*.txt" -exec rm -rf {} \;

 

 

커멘드 명령어로 특정 경로에 파일 생성 후 그 파일 안에 내용 작성

 

 

 

 

Comments