1. Console,
< js >
console.log('로딩중....');
console.clear();
</js >
로딩중.... (없어짐) |
< js >
//개발시 콘솔 사용법
console.log('log'); //개발
console.log('info'); //정보
console.warn('warn'); // 경고
console.error('error'); // 에러, 사용자 에러, 시스템 에러
</js >
log info warn error |
< js >
// assert(조건을 만족하지 않으면 에러 메세지를 출력)
console.assert(2===2,'두 값이 달라요!'); // 값이 출력되지 않음
console.assert(2===3,'두 값이 달라요!'); // 값이 출력됨
</js >
Assertion failed: 두 값이 달라요! |
< js >
// 객체 출력
const user = {userid:'apple',name:'김사과',age:20,company:{name:'홍콩반점',addr:'한국'}};
console.log(user);
console.table(user);
console.dir(user,{showHidden:true, depth:0, color:false});
// 옵션을 줄 수 있는 콘솔
</js >
{ userid: 'apple',name: '김사과', age: 20, company: { name: '홍콩반점', addr: '한국' }} ┌─────────┬────────────┬────────┬──────────┐ │ (index) │ name │ addr │ Values │ ├─────────┼────────────┼────────┼──────────┤ │ userid │ │ │ 'apple' │ │ name │ │ │ '김사과' │ │ age │ │ │ 20 │ │ company │ 'SK' │ '서울 중구' │ │ │ └─────────┴────────────┴────────┴──────────┘ { userid: 'apple', name: '김사과', age: 20, company: [Object] } |
< js >
function func1(){
func2();
}
function func2(){
func3();
}
function func3(){
console.log('func3() 실행!');
console.trace();
}
func3();
</js >
func3() 실행! Trace at func3 (C:\Sarr\KDT\Web\JavaScript\Day6\9_console.js:33:13) at Object.<anonymous> (C:\Sarr\KDT\Web\JavaScript\Day6\9_console.js:36:1) at Module._compile (node:internal/modules/cjs/loader:1369:14) at Module._extensions..js (node:internal/modules/cjs/loader:1427:10) at Module.load (node:internal/modules/cjs/loader:1206:32) at Module._load (node:internal/modules/cjs/loader:1022:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 |
2. This
- global
- 모든 모듈에서 접근 가능한 전역 객체
- 브라우저에서의 window 객체와 유사
- 모든 전역 프로퍼티가 포함
< js >
function hello(){
console.log(this); //global 객체 정보
console.log(this===global); //true
}
hello();
// this: global 객체_최상위 객체
// 사용하게 되면 덮어짐
</js >
global: [Circular *1], clearImmediate: [Function: clearImmediate], setImmediate: [Function: setImmediate] { [Symbol(nodejs.util.promisify.custom)]: [Getter] }, clearInterval: [Function: clearInterval], clearTimeout: [Function: clearTimeout], setInterval: [Function: setInterval], setTimeout: [Function: setTimeout] { [Symbol(nodejs.util.promisify.custom)]: [Getter] }, queueMicrotask: [Function: queueMicrotask], structuredClone: [Function: structuredClone], atob: [Getter/Setter], btoa: [Getter/Setter], performance: [Getter/Setter], fetch: [Getter/Setter], crypto: [Getter] } true |
- JSON 파일은 모듈: 다른 파일에서 import 시켜 쓸 수 있음
< js >
class ClassA {
constructor(num){
this.num=num;
}
classAMethod(){
console.log('=============');
console.log(this);
console.log('=============');
}
}
const classA=new ClassA(10);
classA.classAMethod();
console.log('=============');
console.log(this);
//아무것도 안나옴
//함수안에서 찍으면 글로벌객체로 나옴
//클래스에서 객체 주소 가리킴
console.log(this===module.exports); //true
</js >
============= ClassA { num: 10 } ============= ============= {} true |
- 모듈 사용하기(1)_ required()
< js >
const counter=require('./1_counter1.js');
//가져다쓸 모듈명, js는 생략가능
counter.increase();
counter.increase();
counter.increase();
counter.increase();
console.log(counter.getCount());
</js >
4 |
- 모듈 사용하기(2)_ 패키지
더보기
- npm 라이브러리 사이트: https://www.npmjs.com/
- 패키지 생성하는 방법
[terminal창] [입력] > npm [입력] > npm init Press ^C at any time to quit. package name: (day6) <엔터> version: (1.0.0) <엔터> description: <엔터> entry point: (10_this.js) <엔터> test command: <엔터> git repository: <엔터> keywords: <엔터> author: <엔터> license: (ISC) About to write to C:\Sarr\KDT\Web\JavaScript\Day6\package.json: <엔터> [출력] { "name": "day6", "version": "1.0.0", "description": "", "main": "10_this.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this OK? (yes) <엔터> !!package.json 생성 완료!! |
< package.json >
{
"name": "day6",
"version": "1.0.0",
"description": "",
"main": "10_this.js",
"type": "module", //추가
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
< counter.js >
let count = 0;
export function increase(){
count++;
}
export function getCount(){
return count;
}
</js >
< js >
import { increase, getCount } from "./counter2";
increase();
increase();
increase();
console.log(getCount());
</js >
(node:11948) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use `node --trace-warnings ...` to show where the warning was created) C:\Sarr\KDT\Web\JavaScript\Day6\12_module2.js:1 import { increase, getCount } from "./counter2"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:128:18) at wrapSafe (node:internal/modules/cjs/loader:1280:20) at Module._compile (node:internal/modules/cjs/loader:1332:27) at Module._extensions..js (node:internal/modules/cjs/loader:1427:10) at Module.load (node:internal/modules/cjs/loader:1206:32) at Module._load (node:internal/modules/cjs/loader:1022:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 Node.js v20.12.2 PS C:\Sarr\KDT\Web\JavaScript\Day6> |
< js >
import * as counter from './counter2/js';
increase();
increase();
increase();
console.log(getCount());
</js >
(node:5456) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use `node --trace-warnings ...` to show where the warning was created) C:\Sarr\KDT\Web\JavaScript\Day6\12_module2.js:8 import * as counter from ' ./counter2/js'; ^^^^^^ SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:128:18) at wrapSafe (node:internal/modules/cjs/loader:1280:20) at Module._compile (node:internal/modules/cjs/loader:1332:27) at Module._extensions..js (node:internal/modules/cjs/loader:1427:10) at Module.load (node:internal/modules/cjs/loader:1206:32) at Module._load (node:internal/modules/cjs/loader:1022:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 Node.js v20.12.2 |
- ㅇ호
< js >
//import * as path from path;
const path=require('path');
console.log(__dirname); // 현재 디렉토리
console.log(__filename) // 현재 파일
// Windows: 'C:\Sarr\KDT\Web\JavaScript\Day6\13_path.js'
// POSIX(Unix, Linux, Mac): 'Sarr\KDT\Web\JavaScript\Day6\13_path.js'
</js >
C:\Sarr\KDT\Web\JavaScript\Day6 C:\Sarr\KDT\Web\JavaScript\Day6\13_path.js |
< js >
console.log(path.sep); // window는 \, 맥은 아마도 /
console.log(path.delimiter); //;
console.log(path.basename(__filename)); //13_path.js
console.log(path.basename(__filename,'.js')); //13_path
console.log(path.dirname(__filename,)); // 'C:\user\temp\10-path.js'
console.log(path.extname(__filename)); //.js
</js >
\ ; 13_path.js 13_path C:\Sarr\KDT\Web\JavaScript\Day6 .js |
< js >
const parsed = path.parse(__filename);
console.log(parsed);
console.log(parsed.base);
console.log(parsed.ext);
</js >
{ root: 'C:\\', dir: 'C:\\Sarr\\KDT\\Web\\JavaScript\\Day6', base: '13_path.js', ext: '.js', name: '13_path' } 13_path.js .js |
< js >
//문자열
const str=path.format(parsed);
console.log(str);
console.log('isAbsolute: ',path.isAbsolute(__dirname)); //true
// 물리적(절대) 경로가 맞다는 의미
console.log('isAbsolute: ',path.isAbsolute('../')); //false, 상대경로라서...
</js >
C:\Sarr\KDT\Web\JavaScript\Day6\13_path.js isAbsolute: true isAbsolute: false |
3. file
< js >
const fs=require('fs');
// 동기식: 에러 처리 꼭 해야함
try{
fs.renameSync('./test.txt','./new_test.txt');
}catch(e){
console.error(e);
}
console.log('정상적인 종료!')
</js >
정상적인 종료!! [파일명 test.txt -> new_test.txt] |
< js >
// 비동기식: 별도의 에러처리가 필요하지 않음
fs.rename('./new_text.txt','./text.txt', (error)=>{
console.log(error); // 에러가 없어서 null값
});
</js >
null |
< js >
fs.promises
.rename('./test.txt','text-new.txt')
.then(()=>console.log('완료!!'))
.catch(console.error);
console.log('정상적인 종료!!');
// 비동기이므로 파일이름바꾸기가 먼저 콘솔창에 출력된다.
</js >
정상적인 종료!! 완료!! |
- 파일열기
< js >
const fs = require('fs').promises;
// 파일 읽기
fs.readFile('./new_test.txt', 'utf-8')
.then((data) => console.log(data))
.catch(console.error);
</js >
안녕하세요! 자바스크립트! |
< js >
const fs = require('fs').promises;
// 파일 출력
fs.writeFile('./write.txt','Hello Node.js! 파일 출력입니다!')
.catch(console.error);
</js >
- dfg
< js >
// 파일 추가 출력
fs.appendFile('./write.txt','\r\n추가로 글을 입력합니다!')
.catch(console.error);
</js >
- 파일복사
< js >
// 파일복사
fs.copyFile('./new_test.txt','./test.txt')
.catch(console.error);
</js >
< js >
//디렉토리 생성
fs.mkdir('sub')
.catch(console.error);
</js >
< js >
//디렉토리 읽기
fs.readdir('./')
.then(console.log)
.catch(console.error);
</js >
[Error: EEXIST: file already exists, mkdir 'C:\Sarr\KDT\Web\JavaScript\Day6\sub'] { errno: -4075, code: 'EEXIST', syscall: 'mkdir', path: 'C:\\Sarr\\KDT\\Web\\JavaScript\\Day6\\sub' } [ '10_this.js', '11_module1.js', '12_module2.js', '13_path.js', '14_file.js', '14_file_me.js', '15_fileIO.js', '1_timeout.js', '2_promise.js', '3_promise-egg.js', '4_promise-all.js', '5_async.js', '6_async2.js', '7_json.js', '8_json2.js', '9_console.js', '9_fetch.html', 'counter1.js', 'counter2.js', 'new_test.txt', 'package.json', 'sub', 'test.txt', 'today.js', 'write.txt' ] |
'Web > Node.js' 카테고리의 다른 글
07. http 모듈, 템플릿 엔진 (0) | 2024.04.24 |
---|---|
06. 버퍼(buffer), 스트림(Steam) (0) | 2024.04.24 |
04. JSON (0) | 2024.04.23 |
03. timeout, promise, async (0) | 2024.04.23 |
02. 이터레이터, 이터러블, 스프레드 (0) | 2024.04.19 |