티스토리 뷰
웹 브라우저에서는 window 객체가 최상위 객체다.
node.js는 웹 브라우저에서 동작하지 않는다.
따라서 node.js에서의 최상위 객체는 window 객체가 아니며 window 객체가 존재조차 하지 않다.
대신, 전역 변수, 전역 객체와 전역 함수를 갖고 있다.
전역 변수 출력하기
console.log("filename", __filename);
console.log("dirname", __dirname);
위의 코드를 실행 시,
현재 실행 파일의 이름과 파일 디렉토리를 출력해준다.
console 객체 이용하여 내용 출력하기
console.log("매개변수의 갯수가 부족하면 걍 스트링 %d가 출력된다.");
console.log('%d + %d = %d !! %d', 273, 52, 273+52); // 273 + 52 = 325 !! %d
console.log('문자열 : %s', 'Hello World!', '이렇게 또 입력해도 제대로 출력됨', '!@#!@#!@#');
// 문자열 : Hello World! 이렇게 또 입력해도 제대로 출력됨 !@#!@#!@#
console 객체는 콘솔에 출력하는 것과 관련된 전역 객체다.
process 객체이용하여 프로그램 만들기
process 객체는 프로그램과 관련된 정보를 나타내는 객체다.
다음은 프로그램 실행 시 매개변수들을 출력하며
--exit 문자열이 매개변수로 입력 시 자동으로 프로그램을 종료시키는 내용의 코드다.
process.argv.forEach(function(item, index) {
// 출력
console.log(index + ' : ' + typeof(item) + ':', item);
// --exit 있을 때
if (item == '--exit') {
var exitTime = Number(process.argv[index+1]);
setTimeout(function() {
process.exit();
}, exitTime);
}
});
코드에서 알 수 있듯이
process 객체의 argv 프로퍼티는
프로그램의 매개변수를 array로 갖고 있다.
exports 객체 이용해여 모듈 생성하기
exports 객체는 모듈과 관련된 객체다.
node.js는 exports 객체를 사용하여 기능을 확장할 수 있다.
// module.js
exports.abs = function(number) {
if ( 0 < number) {
return number;
} else {
return -number;
}
};
exports.circleArea = function(radius) {
return radius * radius * Math.PI;
}
// main.js
var module = require('./module.js'); // 모듈 추출
console.log('abs(-123): %d', module.abs(-123));
console.log('circleArea(3) : %d', module.circleArea(3));
위의 예제에서 볼 수 있듯이
exports 객체를 이용해서 모듈을 생성하면 되고
require 메소드를 통해 모듈을 불러와 사용하면 된다.
'정리하기 > 모던웹을 위한 Node.js' 카테고리의 다른 글
외부 모듈 (0) | 2017.06.06 |
---|---|
http 모듈 (0) | 2017.05.28 |
이벤트 (0) | 2017.05.20 |
Node.js 개요 (0) | 2017.05.11 |
- Total
- Today
- Yesterday
- MarionetteJS
- framework
- 외부모듈
- 함수
- nextTick
- 원하는것이있다면끝까지버텨라
- node.js
- vuex
- Android
- vue.js
- mocha.js
- marionetts.js
- angular
- common.js
- browserify
- javascript
- vue
- 자바스크립트
- awe-some
- #가상머신
- awesome-vue
- eventbus
- backbone.js
- git tag
- 뉴욕
- node
- Typescript
- nodejs
- js
- AndroidContext
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |