현재 경로와 파일이름 읽기
const path = require("path");
console.log(__dirname);
console.log(__filename);
윈도우라서 위와 같이 떴고,
유닉스 계열(맥, 리눅스)이었다면
위와 같이 표기된다.
'NodeJS' 카테고리의 다른 글
[NodeJS] Timer (0) | 2022.06.12 |
---|---|
[Node.js] Events `EventEmitter` (0) | 2022.06.05 |
현재 경로와 파일이름 읽기
const path = require("path");
console.log(__dirname);
console.log(__filename);
윈도우라서 위와 같이 떴고,
유닉스 계열(맥, 리눅스)이었다면
위와 같이 표기된다.
[NodeJS] Timer (0) | 2022.06.12 |
---|---|
[Node.js] Events `EventEmitter` (0) | 2022.06.05 |
터미널 : npm init --yes
package.json
{
"name": "nodejs",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module", //자바스크립트 자체적으로 쓰는 모듈을 쓸 것이다.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
let num = 1;
setInterval(() => {
console.log(num++);
}, 1000);
setInterval은 따로 중지하지 않는 이상, 계속 실행된다.
/**
* The `timer` module exposes a global API for scheduling functions to
* be called at some future period of time. Because the timer functions are
* globals, there is no need to call `require('timers')` to use the API.
*
* The timer functions within Node.js implement a similar API as the timers API
* provided by Web Browsers but use a different internal implementation that is
* built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).
* @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/timers.js)
*/
declare module 'timers' {
import { Abortable } from 'node:events';
import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises';
interface TimerOptions extends Abortable {
/**
* Set to `false` to indicate that the scheduled `Timeout`
* should not require the Node.js event loop to remain active.
* @default true
*/
ref?: boolean | undefined;
}
let setTimeout: typeof global.setTimeout;
let clearTimeout: typeof global.clearTimeout;
let setInterval: typeof global.setInterval;
let clearInterval: typeof global.clearInterval;
let setImmediate: typeof global.setImmediate;
let clearImmediate: typeof global.clearImmediate;
global {
namespace NodeJS {
// compatibility with older typings
interface Timer extends RefCounted {
hasRef(): boolean;
refresh(): this;
[Symbol.toPrimitive](): number;
}
interface Immediate extends RefCounted {
/**
* If true, the `Immediate` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
_onImmediate: Function; // to distinguish it from the Timeout class
}
interface Timeout extends Timer {
/**
* If true, the `Timeout` object will keep the Node.js event loop active.
* @since v11.0.0
*/
hasRef(): boolean;
/**
* Sets the timer's start time to the current time, and reschedules the timer to
* call its callback at the previously specified duration adjusted to the current
* time. This is useful for refreshing a timer without allocating a new
* JavaScript object.
*
* Using this on a timer that has already called its callback will reactivate the
* timer.
* @since v10.2.0
* @return a reference to `timeout`
*/
refresh(): this;
[Symbol.toPrimitive](): number;
}
}
function setTimeout<TArgs extends any[]>(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout;
namespace setTimeout {
const __promisify__: typeof setTimeoutPromise;
}
function clearTimeout(timeoutId: NodeJS.Timeout | undefined): void;
function setInterval<TArgs extends any[]>(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer;
namespace setInterval {
const __promisify__: typeof setIntervalPromise;
}
function clearInterval(intervalId: NodeJS.Timeout | undefined): void;
function setImmediate<TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate;
// util.promisify no rest args compability
// tslint:disable-next-line void-return
function setImmediate(callback: (args: void) => void): NodeJS.Immediate;
namespace setImmediate {
const __promisify__: typeof setImmediatePromise;
}
function clearImmediate(immediateId: NodeJS.Immediate | undefined): void;
function queueMicrotask(callback: () => void): void;
}
}
declare module 'node:timers' {
export * from 'timers';
}
let num = 1;
const interval = setInterval(() => {
console.log(num++);
}, 1000);
setTimeout(() => {
console.log("TimeOut!");
clearInterval(interval);
}, 6000);
다만 타이머 계열 api들 보다
process.nextTick(()=>{}) 이 콜스택에 들어가는 최우선 순위를 가장 먼저 가져간다.
* setTimeout과 setImmediate는 거의 동일하게 작용
console.time()~console.timeEnd()로 실행~완료 시간을 측정할 수 있다.
console.time("");
setTimeout(() => {
console.timeEnd("");
}, 0); // 1.959ms 등 다양한 숫자가 나오면서 완벽히 0초를 보장하지는 않는다.
console.time("");
setImmediate(() => {
console.timeEnd("");
}, 0); //역시나 2.391ms 등 다양한 숫자가 나오면서 완벽히 0초를 보장하지는 않는다.
완벽한 0초를 보장할 수 없는 이유 : 콜스택이 텅텅 비었다고 보장 받을 때까지 기다리는 시간이 있기 때문이다.
[NodeJS] path (0) | 2022.06.12 |
---|---|
[Node.js] Events `EventEmitter` (0) | 2022.06.05 |
https://edykim.com/ko/post/events-eventemitter-translation-in-node.js/
Node.js의 Events `EventEmitter` 번역
는 Node.JS에 내장되어 있는 일종의 옵저버 패턴 구현이다. node 뿐만 아니라 대부분의 프레임워크나 라이브러리에서 이 구현을 쓰거나 유사한 구현을 활용하고 있는 경우가 많다. DOM Event Listener를
edykim.com
https://www.huskyhoochu.com/nodejs-eventemitter/
Nodejs EventEmitter 뜯어보기
Node.js 소스 코드를 살펴보면서 EventEmitter가 어떻게 돌아가는지 확인합니다
www.huskyhoochu.com
https://github.com/primus/eventemitter3
GitHub - primus/eventemitter3: EventEmitter3 - Because there's also a number 2. And we're faster.
EventEmitter3 - Because there's also a number 2. And we're faster. - GitHub - primus/eventemitter3: EventEmitter3 - Because there's also a number 2. And we're faster.
github.com
https://nodejs.org/api/events.html
Events | Node.js v18.3.0 Documentation
Events# Source Code: lib/events.js Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be call
nodejs.org
[NodeJS] path (0) | 2022.06.12 |
---|---|
[NodeJS] Timer (0) | 2022.06.12 |