오늘은 유튜브의 The Net Ninja의 Node.js Crash Course를 수강하면서 학습한 내용을 정리해보았습니다.

// VSCode에 다음과 같이 입력 후 출력
console.log(global)
//Expected Output on terminal
Object [global] {
global: [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
},
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
}
}
console.log(__dirname__)을 하면 폴더의 경로가 출력 됨console.log(__filename__)을 하면 파일의 경로가 출력 됨 // 아래 2줄은 people.js 파일의 코드임
const people = ['Si', 'Que', 'Dong', 'Bin', 'Goran']
console.log(people)
//아래 3 줄은 modules.js 파일의 코드임
const xyz = require("./people"); //people 파일이 실행됨
console.log(xyz); // 콘솔 창에 빈 obj{}를 출력
console.log(people) // people 변수가 없다고 에러 발생
node modules를 입력하면 modules 파일의 1번 줄 때문에 people.js 파일이 실행되면서 Console 창에 ['Si', 'Que', 'Dong', 'Bin', 'Goran']이 출력 됨 // 아래 2줄은 people.js 파일의 코드임
const people = ['Si', 'Que', 'Dong', 'Bin', 'Goran']
console.log(people)
module.exports = 'hello'
//아래 3 줄은 modules.js 파일의 코드임
const xyz = require("./people"); //people 파일이 실행됨
console.log(xyz); // 'hello'가 출력 됨
node modules를 입력하여 실행하면, modules.js에 require로 people.js를 불러오기 때문에 people.js 파일이 실행 되어 콘솔창에 ['Si', 'Que', 'Dong', 'Bin', 'Goran']이 출력 되고const xyz는 module.exports의 값인 'hello'를 받아오기 때문에 마찬가지로 콘솔 창에 hello가 출력 됨 module.exports를 한 값(혹은 변수)이 import 됨// 1. 아래는 people.js 파일의 코드임
const people = ['Si', 'Que', 'Dong', 'Bin', 'Goran'];
const ages = [20, 25, 30, 35];
module.exports = {
people: people, //exports 객체에 people key에 people을 할당
age: age
}
// 2. 아래는 위 people.js를 Refactoring 한 코드 임
const people = ['Si', 'Que', 'Dong', 'Bin', 'Goran'];
const ages = [20, 25, 30, 35];
module.exports = {
people, age
}
/* module.exports의 key와 property 명이 같으면 하나로 입력 가능
------------------------------------------------------*/
// 3. 아래 3 줄은 modules.js 파일의 코드임
const xyz = require("./people"); //people 파일을 불러옴(실행)
console.log(xyz.people, xyz.age);
// 각각 people 배열과 age 배열이 출력 됨
//4. 위 modules.js의 xyz에 Destructuring을 활용하는 방법
const { people, age } = require("./people")
console.log(people, age)
/* people.js에서 불러온 people과 age의 변수를 destructuring을
통하여 변수 선언을 하면, 위와 같이 people, age를 활용할 수 있음 */