https://www.youtube.com/watch?v=RLtyhwFtXQA





const EventEmitter = require("events");
const eventEmitter = new EventEmitter();
eventEmitter.on("tutorial", () => {
console.log("tutorial event has occrued");
});
eventEmitter.emit("tutorial");

const EventEmitter = require("events");
const eventEmitter = new EventEmitter();
eventEmitter.on("tutorial", (num1, num2) => {
console.log(num1 + num2);
});
eventEmitter.emit("tutorial", 1, 2);
class Person extends EventEmitter {
constructor(name) {
super();
this._name = name;
}
get name() {
return this._name;
}
}
let pedro = new Person("Pedro");
let christina = new Person("Christina");
christina.on("name", () => {
console.log("my name is " + christina.name);
});
pedro.on("name", () => {
console.log("my name is " + pedro.name);
});
pedro.emit("name");
christina.emit("name");

fs에 대해서 조사를 해보았다.
fs 라이브러리를 소환해서 node에게 파일을 읽는 법을 가르쳐주는 것이다. 간단하게 말하자면 앞의 라이브러리를 쓰는법을 잘 알아야한다고 생각한다.
https://www.youtube.com/watch?v=U57kU311-nE
https://www.youtube.com/watch?v=jAAmI5gMlVo
const printString = (string, callback) => {
setTimeout(
() => {
console.log(string)
callback()
},
Math.floor(Math.random() * 100) + 1
)
}
const printAll = () => {
printString("A", () => {
printString("B", () => {
printString("C", () => {})
})
})
}
printAll() // now what do you expect?
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log(string)
resolve()
},
Math.floor(Math.random() * 100) + 1
)
})
}
const printAll = () => {
printString("A")
.then(() => {
return printString("B")
})
.then(() => {
return printString("C")
})
}
printAll()

function gotoCodestates() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('1. go to codestates') }, Math.floor(Math.random() * 100) + 1)
})
}
function sitAndCode() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('2. sit and code') }, Math.floor(Math.random() * 100) + 1)
})
}
function eatLunch() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('3. eat lunch') }, Math.floor(Math.random() * 100) + 1)
})
}
function goToBed() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('4. goToBed') }, Math.floor(Math.random() * 100) + 1)
})
}
gotoCodestates()
.then(data => {
console.log(data)
sitAndCode()
.then(data => {
console.log(data)
eatLunch()
.then(data => {
console.log(data)
goToBed()
.then(data => {
console.log(data)
})
})
})
})
여기서 본것처럼 데이터가 넘어가긴하는데
좀 쓰기가 힘들다.
그렇기 때문에 chain을 걸어주게 된다면
코드를 한줄에 쓸수있게 된다. 중요한것은 다음에
넘어가는 인자가 프로미스가 되어야하기 때문에
return을 계속 해줘야한다는 점이 있다.
gotoCodestates()
.then(data => {
console.log(data)
return sitAndCode()
})
.then(data => {
console.log(data)
return eatLunch()
})
.then(data => {
console.log(data)
return goToBed()
})
.then(data => {
console.log(data)
})
리턴값을 넣어준다.
순서대로 출력하게 await를 붙여준다.
제일 간단한 방법이다.
await라는 것을 통하여서 순서를 주었으므로
연결되지 않아도 순서대로 출력되게 된다.
const result = async () => {
const one = await gotoCodestates();
console.log(one);
const two = await sitAndCode();
console.log(two);
const three = await eatLunch();
console.log(three);
const four = await goToBed();
console.log(four);
};
result();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

8.5: Saving Data to JSON File with Node.js - Programming with Text
https://www.youtube.com/watch?v=6iZiqQZBQJY&t=114s
Nodejs가 '파일을 읽는' 방법입니다.
그러니까 한꺼번에 파일을 담아둘수 없으니까 다른데서 파일을 불러오는데 컴퓨터가 인간의 언어를 잘 못알아들으니까
변환해서 불러오는거다.
JSON.parse로 불러온다.
var fs = require("fs");
var data = fs.readFileSync("word.json");
var words = JSON.parse(data);
console.log(words);
Node JS Tutorial for Beginners #9 - Reading & Writing Files (fs)
https://www.youtube.com/watch?v=U57kU311-nE&t=393s
const fs = require("fs");
const readMe = fs.readFileSync("word.txt", "utf8");
console.log(readMe);
const fs = require("fs");
fs.readFile("word.txt", "utf8", function (err, data) {
console.log(data);
});
console.log("test");
게다가 fs.readFile이 async 비동기라서
test가 먼저 출력된다.


const fs = require("fs");
const getDataFromFile = function (filePath, callback) {
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
}); // 문서를 불러와라 그다음엔? 에러가 있으면 첫번째에 넣어서 실행, 없으면 두번째에 데이터가 있으니 두번째에 넣어서 실행
};
getDataFromFile("README.md", (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
module.exports = {
getDataFromFile,
};
여기서 왜 callback인자에 2개가 오는지 고민을 많이 해봐야겠다.
callback을 했는데 인자가 2개왔는데 앞에건 버리고 뒤에 있는걸 실행시킨다 이런건가?
Promise-version
const fs = require("fs");
const getDataFromFilePromise = (filePath) => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
getDataFromFilePromise("README.md").then((data) => console.log(data));
module.exports = {
getDataFromFilePromise,
};
Basic-Chaining 하는법
const path = require("path");
const { getDataFromFilePromise } = require("./02_promiseConstructor");
const user1Path = path.join(__dirname, "files/user1.json");
const user2Path = path.join(__dirname, "files/user2.json");
// HINT: getDataFromFilePromise(user1Path) 맟 getDataFromFilePromise(user2Path) 를 이용해 작성합니다
const readAllUsersChaining = () => {
let arr = [];
return getDataFromFilePromise(user1Path)
.then((user1) => {
arr.push(JSON.parse(user1));
return getDataFromFilePromise(user2Path);
})
.then((user2) => {
arr.push(JSON.parse(user2));
return arr;
})
.catch((err) => console.log(err));
};
readAllUsersChaining();
module.exports = {
readAllUsersChaining,
};
https://www.youtube.com/watch?v=QO4NXhWo_NM&list=PLRqwX-V7Uu6bKLPQvPRNNE65kBL62mVfx
fetch MDN