나의 발자취
node.js 파일 간 함수 전달 (module.exports), 파일 읽고 쓰기 본문
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 {} \;
커멘드 명령어로 특정 경로에 파일 생성 후 그 파일 안에 내용 작성
'Backend' 카테고리의 다른 글
[node.js] HTML 템플릿 엔진 PUG, HandleBars, EJS (1) | 2024.09.26 |
---|---|
[node.js]express, nodemon 이용하기 (1) | 2024.09.26 |
node.js - npm모듈 설치하기 (0) | 2024.09.24 |
데이터베이스 모델 설계, insert into-do update set (0) | 2024.09.13 |
SQL 기본 쿼리 (2) 숫자 관련 메서드: length(), concat(), left(), right(), split_part(), lpad(), rpad(), trim(), position(), repeat(), replace(), reverse(), 올림/내림/반올림/제곱근/ 절댓값/모듈러/랜덤 (1) | 2024.09.11 |
Comments