[JS] chapter20. λΉλκΈ°2 - node.js
π λΉλκΈ°
λΉλκΈ° μ²λ¦¬λ, νΉμ μ½λμ μ€νμ΄ μλ£λ λκΉμ§ κΈ°λ€λ¦¬μ§ μκ³ λ€μ μ½λλ₯Ό μννλ κ²
jsλ μ±κΈ μ€λ λ κΈ°λ° λμ μΈμ΄λΌμ λκΈ°μ μλμ΄μ§λ§ νκ²½(λ°νμ)μμ λΉλκΈ° μ²λ¦¬λ₯Ό λμμ£ΌκΈ° λλ¬Έμ
λΉλκΈ° μ²λ¦¬ λν κ°λ₯νλ€.
π» node.js λͺ¨λ
λΈλΌμ°μ μμ μ¬μ©ν μ μλ λΉλκΈ° νλ¦μ νμ΄λ¨Έ λλ dom μ΄λ²€νΈ λ± λ€μ νμ μ μ΄μ§λ§,
node.js κ²½μ° λ§μ APIκ° λΉλκΈ°λ‘ μμ±λμ΄ μλ€.
node.js λ?
λΉλκΈ° μ΄λ²€νΈ κΈ°λ° javascript λ°νμ
node.js λͺ¨λ
λͺ¨λ - μ΄λ€ κΈ°λ₯μ 쑰립ν μ μλ νν
fs λͺ¨λ - pcμ νμΌμ μ½κ±°λ μ μ₯νλ λ±μ μΌμ λμμ€
λ΄μ₯ λͺ¨λμ μ¬μ©νλ λ°©λ² - λ§ν¬
Node.js v16.14.2 Documentation
Index | Node.js v16.19.0 Documentation
nodejs.org
π λ΄μ₯ λͺ¨λ - fs λͺ¨λ
readFile - νμΌμ μ½μ λμ μ°λ λ©μλ
writeFile - νμΌμ μ μ₯ν λμ μ°λ λ©μλ
<script src="λΆλ¬μ€κ³ μΆμ_μ€ν¬λ¦½νΈ.js"></script> // λͺ¨λμ μ¬μ©νκΈ° μν΄ λΆλ¬μ€λ κ³Όμ
// js μ½λ μλ¨μ require ꡬ문μ μ΄μ©νμ¬ λ€λ₯Έ νμΌμ λΆλ¬μ¨λ€
const fs = require('fs'); // νμΌ μμ€ν
λͺ¨λμ λΆλ¬μ΅λλ€
const dns = require('dns'); // DNS λͺ¨λμ λΆλ¬μ΅λλ€
// μ΄μ fs.readFile λ©μλ λ±μ μ¬μ©ν μ μμ΅λλ€!
π 3rd-party λͺ¨λμ μ¬μ©νλ λ°©λ²
μλ νν° λͺ¨λ - ν΄λΉ νλ‘κ·Έλλ° μΈμ΄μμ 곡μμ μΌλ‘ μ 곡νλ λΉνΈμΈ λͺ¨λμ΄ μλ λͺ¨λ μΈλΆ λͺ¨λ
μ€μ΅) underscore μ€μΉ ν μ¬μ©
npm install underscore // ν°λ―Έλμμ underscore μ€μΉ
const _ = require('underscore'); // λ΄μ₯ λͺ¨λ μ¬μ©νλ― μ¬μ©
π fs.readFile(path[, options], callback)
λ©μλ fs.readFileμ λΉλκΈ°μ μΌλ‘ νμΌ λ΄μ© μ 체λ₯Ό μ½λλ€
μ΄ λ©μλλ₯Ό μ€νν λμλ μ λ¬μΈμλ₯Ό 3κ° λ°λλ€
path : <string> <Buffer> <URL> <integer>
νμΌ μ΄λ¦μ μ λ¬μΈμλ‘ λ°λλ€ μΌλ°μ μΌλ‘ string νμ μ λ°λλ€
options : <Object> <string>
λ£μ μλ μκ³ λ£μ§ μμ μλ μλ€. λκ΄νΈλ μ νμ μ λ¬μΈμλ₯Ό μλ―Έ
λ¬Έμμ΄ λλ κ°μ²΄ ννλ‘ λ°λλ€. ex) utf-8
callback : <Function>
μ½λ°± ν¨μλ₯Ό μ λ¬, νμΌμ μ½κ³ λ νμ λΉλκΈ°μ μΌλ‘ μ€νλλ ν¨μ
μ½λ°± ν¨μλ λ κ°μ§ λ§€κ²λ³μκ° μ‘΄μ¬
- err \<Error> | \<AggregateError>
- data \<string> | \<Buffer>
errλ null μ΄ λλ©°, dataλ λ¬Έμμ΄μ΄λ bufferλΌλ κ°μ²΄κ° μ λ¬λλ€. dataλ νμΌ λ΄μ©
μμ μ½λ
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // μλ¬λ₯Ό λμ§λλ€.
}
console.log(data);
});