[Lambda] node-gyp
C++ Addons as AWS Lambda functions
https://nodeaddons.com/c-addons-as-aws-lambda-functions/
C++ Addons as AWS Lambda functions
C++ Addons as AWS Lambda functions
nodeaddons.com
Cross-compile node module with native bindings with node-gyp
I'm using AWS Lambda, which involves creating an archive of my node.js script, including the node_modules folder and uploading that to their infrastructure to run. This works fine, except when it ...
stackoverflow.com
'JS > Node.js' 카테고리의 다른 글
[정리] 아하 REST API 서버 개발 #3 (0) | 2019.03.31 |
---|---|
[정리] 아하 REST API 서버 개발 #1, #2 (0) | 2019.03.31 |
[Node.js] How to store emoji in MySQL (0) | 2019.02.03 |
[정리] 아하 REST API 서버 개발 #3
이 글은 아하 REST API 서버 개발 의 내용을 토대로 정리하고, 궁금한 것을 공부한 내용입니다..
Express 는 사실 미들웨어 프레임워크. 시작과 끝이 미들웨어이기 때문에.
미들웨어 함수는 요청 객체 (req), 응답 객체 (res) 그리고 다음 미들웨어를 실행하는 next 함수로, 클라이언트 요청을 처리하여 응답하는 과정사이에 거쳐가는 함수 라고 말 할 수 있으며, next 함수를 이용해서 다음 미들웨어로 순서를 넘길 수 있다.
또한, 미들웨어는 순차적으로 실행되므로 미들웨어의 순서가 매우매우 중요하다.
미들웨어의 구조
const app = express();
app.use(express.json())
app.use('/', indexRouter)
app.use(function(req, res, next) {
next(createError(404))
})
app.js
의 일부 코드인데,app.use()
안에 있는 모든 함수들은 미들웨어라 할 수 있다.사용자의 요청이 올때마다 순서대로 미들웨어를 쭉 타고 내려가며 클라이언트에게 응답을 하게 된다.
또한,
indexRouter
는 라우터임에도 불구하고 use 함수안에 담겨져 있는데, Express 입장에서는 라우트도 하나의 미들웨어 일 뿐이다.
라우터 미들웨어는 express.Router() 인스턴스에 바인드되는 방식으로 동작한다.
Router 객체를 이용해 router.use() 및 router.METHOD() 함수를 사용하여 라우터 레벨 미들웨어를 로드할 수 있다.
또한, Router 객체는 그 자체가 미들웨어이므로 (혹은 똑같은 방식으로 동작하므로) app.use()
나 router.route()
의 인수로 사용될 수 있다.
app.use('/', indexRouter)
app.js
소스에서 라우터 파일이app.use()
에 바인딩 된 것을 확인할 수 있다.
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.json({message: 'Hello A-ha'})
});
module.exports = router;
indexRouter.js
의 경우 위와 같이 작성되어 있는데, 위 그림에서의 미들웨어 구조와 정확하 똑같다.
라우터 미들웨어는 사용자로부터 요청받은 req 객체를 처리한 후 응답 객체 res 를 리턴하는 방식으로 동작한다.
라우터에서의 next 는 에러 처리를 위해 사용된다.
컨트롤러 파일 분리
controllers/index.controller.js
const index = (req, res, next) => res.json({
message: 'Hello A-ha!'
})
export {
index
}
라우팅과 비즈니스 로직을 분리하였다.
위의 코드는 최신 스펙의 js 코드. :
export
routes/index.js
import express from 'express'
import {index} from '../controllers/index.controller'
const router = express.Router()
/* GET home page. */
router.get('/', index)
export default router
module.exports = router;
의 코드를export default router
로 변경
app.js
require('dotenv').config()
import createError from 'http-errors'
import express from 'express'
import cookieParser from 'cookie-parser'
import logger from 'morgan'
import indexRouter from './routes/index'
const app = express()
...
app.use('/', indexRouter)
// catch 404 and forward to error handler
...
// error handler
...
// bin/www 를 그대로 사용하기 위해서 예외적으로 commonJs 문법을 적용
module.exports = app
var express = require('express');
의 코드를import express from 'express'
와 같이 변경하였다.
이렇게 하고 실행을 import 구문 같은 경우에는 nodejs 가 어떻게 해석을 해야 하는지 모른다며 에러가 발생하는데, 최신 스펙의 자바스크립트는 현재 nodejs 버전에서 모두 지원을 하는 것이 아니기 때문이다.
nodejs 가 해석할 수 있도록 친절하게 일면 번역 (트랜스파일) 을 해주는 모듈이 있는데, 그게 그토록 유명한 바벨이다.
바벨 세팅
> npm install -g nodemon
> npm install --save @babel/polyfill
> npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node
프로젝트 루트에.babelrc
파일을 생성한 후,
{
"presets": [
[
"@babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
package.json 파일에서
{
"scripts": {
"start": "nodemon ./bin/www --exec babel-node --presets @babel/preset-env"
}
}
scripts
내용을 수정.
이제 npm start
를 통해 서버를 구동시킬 수 있다.
참고로 Express 는 다음과 같은 미들웨어 유형이 존재한다.
- 애플리케이션 레벨 미들웨어
- 라우터 레벨 미들웨어
- 오류 처리 미들웨어
- 써드파티 미들웨어
라우터를 더욱 세세하게 분리하고 컨트롤러 로직을 작성하고 에러 핸들링을 한곳에서 처리하는 방법
Babel(바벨)은 ES6+ 문법으로 작성된 js파일을 ES5문법으로 작성된 js파일로 만들어주는 작업을 해주는 도구다.
대부분의 브라우저가 ES6문법을 완전히 지원해주지 않기 때문에 ES6문법의 자바스크립트 파일을 사용할 수 없다.
따라서 Babel(바벨)을 이용해서 개발은 ES6로 하되 브라우저는 트랜스 파일링된 ES5문법의 js파일을 사용하게 하는 식의 구성을 갖게 해야한다.
Babel
은 다양한 작은 모듈들로 구성되어 있다. Babel
다양한 모듈을 담는 일종의 상자 역할을 하며 코드를 컴파일 하기 위해 작은 모듈들(ex. presets)을 사용한다.
Reference
- ES6 바벨(babel)을 이용한 트랜스 파일링
- [Tool] (번역) Everything you need to know about BabelJS
- https://babeljs.io/docs/en/ - 공식문서
This is a new feature of NPM called 'scoped packages', which effectively allow NPM packages to be namespaced.
네임스페이스라고 보면 된다.
바벨 7버전부터는 모든 바벨 패키지들이 @babel이라는 네임스페이스 안에 속하게 되었다고 한다.
Reference
- https://stackoverflow.com/questions/36667258/what-is-the-meaning-of-the-at-prefix-on-npm-packages
- BabelJS(바벨)
패키지 스코프
Babel 의 공식 패키지들은 이제 @babel 이라는 패키지 스코프를 사용한다.
babel-cli
babel-core
babel-preset-env
babel-polyfill
@babel/cli
@babel/core
@babel/preset-env
@babel/polyfill
설치시 아래쪽 같이 진행하면 된다.
Reference : https://www.slideshare.net/ssuser2295821/babel-7
Babel includes a polyfill that includes a custom regenerator runtime and core-js.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node
).
This means you can use new built-ins like Promise
or WeakMap
, static methods like Array.from
or Object.assign
, instance methods like Array.prototype.includes
, and generator functions (provided you use the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like String
in order to do this.
바벨을 사용하면 새로운 문법을 구형 자바스크립트 문법으로만 바꿔줍니다. 문법만 바꿔주면 됐지 뭘 더 바라냐고요? 바벨 그 자체로는 ES2015의 새로운 객체(Promise, Map, Set 등등)과 메소드(Array.find
, Object.assign
등등)을 사용할 수 없습니다. 왜냐하면 ES2015에서 처음 생긴 거라 구형 자바스크립트에는 그에 상응하는 코드가 없거든요. 그래서 babel-polyfill을 설치해야 새로운 기능을 사용할 수 있습니다
폴리필은 하나의 프로젝트에 한 번만 사용해야 합니다. 그렇지 않으면 충돌이 발생합니다. 따라서 가장 먼저 로딩되는 스크립트 제일 위에 추가하도록 합시다.
Reference
- https://babeljs.io/docs/en/babel-polyfill](https://babeljs.io/docs/en/babel-polyfill)
- https://www.zerocho.com/category/ECMAScript/post/57a830cfa1d6971500059d5a
@babel/preset-env
is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
.babelrc라는 파일을 만들어 설치한 preset을 연결해줍니다. .babelrc는 바벨에 대해 설정을 하는 파일입니다. 여기에 preset이나 plugin을 연결하면 됩니다. preset은 여러 플러그인의 모음집입니다.
유명한 preset으로는 react나 es2015, es2016, es2017, env, ~~stage-0, stage-1, stage-2, stage-3 ~~등이 있습니다. 7버전부터 stage-0, stage-1, stage-2, stage-3은 deprecated되었습니다. 앞으로는 새로운 스펙은 프리셋 대신 플러그인 형식으로 넣어야 합니다.
react 프리셋은 react 환경(jsx)을 위한 프리셋이고, es2015는 ES2015 문법을 사용할 수 있게 도와주는 플러그인들의 프리셋입니다.
env 프리셋은 한 술 더 떠서 특정한 문법 버전을 입력할 필요 없이, 타겟 브라우저를 입력하면 알아서 사용자가 환경에 맞춰 최신 EcmaScript를 사용할 수 있게 해줍니다
Reference
Babel comes with a built-in CLI which can be used to compile files from the command line.
In addition, various entry point scripts live in the top-level package at @babel/cli/bin
. There is a shell-executable utility script, babel-external-helpers.js
, and the main Babel cli script, babel.js
.
bael-cli
는 command line을 통해 코드를 transpile 할 수 있는 도구.
Reference
- https://babeljs.io/docs/en/babel-cli
- https://jaeyeophan.github.io/2017/05/16/Everything-about-babel/
babel-node is a CLI that works exactly the same as the Node.js CLI, with the added benefit of compiling with Babel presets and plugins before running it.
babel-node는 REPL로도 동작한다.
Reference
Babel 7 + Node.js로 모던 자바스크립트 사용하기
ES6 부터 사용 가능한 모듈 시스템.
정리 : https://ychooni.tistory.com/480
export { a, b, c }
와 같이 내보낸 것은 다른 파일에서 import { a, b, c } from './path'
와 같이 불러올 수 있다.
export default router
와 같이 내보낸 것은 다른 파일에서 import indexRouter from './path'
와 같이 불러올 수 있다.
자바스크립트 개발을 하다보면 require나 import 키워드를 통해 외부 라이브러리를 불러오는 코드를 자주 보게 됩니다. require는 NodeJS에서 사용되고 있는 CommonJS 키워드이고, import는 ES6(ES2015)에서 새롭게 도입된 키워드입니다.
Reference : [http://www.daleseo.com/js-module-require/](
'JS > Node.js' 카테고리의 다른 글
[Lambda] node-gyp (0) | 2019.05.16 |
---|---|
[정리] 아하 REST API 서버 개발 #1, #2 (0) | 2019.03.31 |
[Node.js] How to store emoji in MySQL (0) | 2019.02.03 |
[정리] 아하 REST API 서버 개발 #1, #2
이 글은 아하 REST API 서버 개발 의 내용을 토대로 정리하고, 궁금한 것을 공부한 내용입니다..
빠른 개발 속도
TDD 패러다임에 충실.
express-generator
를 통한 설치.
> npm install -g express-generator
> express restapi
restapi
폴더대 생성되고, 기본적인 파일들이 생성되어 있다.해당 폴더로 이동 후
npm install
을 진행.
package.json
파일에서 "start": "node ./bin/www"
를 통해, express 의 entry point 가 bin 폴더 밑에 위치한 www 파일인 것을 알 수 있다.
dotenv 모듈을 사용하여 node 를 실행하실 때 시스템 변수를 명시적으로 지정할 수 있다.
.env
파일에 필요한 변수를 작성하고 모듈을 로딩하시는 것으로 간단하게 할 수 있다.
dotenv 모듈 로드하기
require('dotenv').config();
.env
파일 기본 설정
NODE_ENV=development
DEBUG=restapi:server
PORT=3000
bin/www 파일은 express 서버를 실행하는 코드라면, app.js 파일은 express 서버가 어떻게 동작해야 하는지를 규정하는 앱 코드이다.
이 프로젝트는 REST API 서버를 구축하는 것이 목표이고, 페이지를 렌더링 할 것이 아니기 때문에, 뷰 엔진과 public 리소스 설정을 걷어낸다.
express 에서 라우트가 어떻게 동작하고 production grade 에서는 어떤 식으로 설계를 할 수 있는지
'JS > Node.js' 카테고리의 다른 글
[Lambda] node-gyp (0) | 2019.05.16 |
---|---|
[정리] 아하 REST API 서버 개발 #3 (0) | 2019.03.31 |
[Node.js] How to store emoji in MySQL (0) | 2019.02.03 |
[JS] import / export
ES6 부터 사용 가능한 모듈 시스템으로 파일이나 모듈 안의 함수나 객체를 export
하는 데 사용된다.
/*** lib.js ***/
export const pi = 3.141592;
export function square(x) {
return x * x;
}
export class Person {
construct(name) {
this.name = name;
}
}
export
키워드로 변수, 함수, 클래스를 외부의 스크립트로 모듈화 시킬 수 있다.
/*** lib.js ***/
const pi = 3.141592;
function square(x) {
return x * x;
}
class Person {
construct(name) {
this.name = name;
}
}
export { pi, square, Person };
한번에
export
처리도 가능하다.
import { pi, square, Person } from './lib';
console.log(pi); // 3.141592653589793
console.log(square(10)); // 100
console.log(new Person('Lee')); // Person { name: 'Lee' }
import
와from
을 통해export
한 것들을 가져올 수 있다.
import * as lib from './lib';
console.log(lib.pi); // 3.141592653589793
console.log(lib.square(10)); // 100
console.log(new lib.Person('Lee')); // Person { name: 'Lee' }
한번에 불러와서 사용도 가능하다.
export
에는 Named export
와 Default export
가 존재.
Named export
는 여러 값을 export
하는 데 유용하다. export
된 이름을 사용하여 import
할 수 있다.
/*** ./controllers/MainController.js ***/
const tag = '[MainController]';
export default {
init() {
console.log(tag, 'init()');
}
}
/*** ./app.js ***/
import MainController from './controllers/MainController.js';
document.addEventListener('DOMContentLoaded', () => {
MainController.init();
});
위와 같이 사용할 수 있다.
default export
는 모듈 당 한개만 있을 수 있으며,default export
로 객체, 함수, 클래스 등이 될 수 있다. "메인" 이라고 할 수 있는 것들을default export
하는 것이 좋다고 하며, 단일 값이나 모듈에 대한 대체값을export
하는 데default export
를 사용해야 한다.
import myDefault, * as myModule from "my-module.js";
// 또는
import myDefault, {foo, bar} from "my-module.js";
default export
된 값이 먼저 선언이 되어야 한다.
import {reallyReallyLongModuleMemberName as shortName} from "my-module.js";
import 'my-modules.js';
'JS > JS(ES6+)' 카테고리의 다른 글
[JS] 느낌표로 시작하는 함수 (0) | 2019.02.11 |
---|---|
[JS] require(), module.exports, exports (0) | 2019.01.25 |
[JS] Symbol (ES6) (0) | 2019.01.20 |
[JS] 느낌표로 시작하는 함수
function() {}
함수의 선언문이다.
const a = !function() {}();
console.log(a); // true
function
앞에 느낌표를 붙이게 되면, 표현식으로 다루게 된다. 즉, 위의 코드는 함수 표현식이며, 함수를 즉시 실행하기 위한 코드 이기도 하다.또한 위의 코드는 리턴되는 값의
!
가 적용된 값이 리턴된다.undefined
에!
가 적용되어true
가 리턴되었다.
const b = (function(){})();
console.log(b); // undefined
함수를 즉시 실행시키는 또 다른 코드. 이 코드의 바이트를 조금이라도 아끼기 위해
느낌표로 시작하는 함수
가 사용되고 있다고 한다. 또한 위의 코드는 함수가 리턴하는 값을 그대로 리턴한다.
Reference
https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function
[http://afrobambacar.github.io/2014/09/느낌표로-시작하는-자바스크립트-함수.html](
'JS > JS(ES6+)' 카테고리의 다른 글
[JS] import / export (0) | 2019.02.11 |
---|---|
[JS] require(), module.exports, exports (0) | 2019.01.25 |
[JS] Symbol (ES6) (0) | 2019.01.20 |
[Node.js] How to store emoji in MySQL
DataBase Schema 에서 default collation 을 utf8 - default collation 에서 utf8mb4 - utf8mb4_unicode_ci 로 변경
테이블의 특정 칼럼의 collation 을 Table default 에서 utf8mb4 - utf8mb4_unicode_ci 로 변경
NodeJs - sql connection options 에 charset : 'utf8mb4' 추가
포스트맨에서는 정상적으로 보임.
utf8 인코딩은 3바이트까지 지원하는데 이모티콘은 4바이트를 차지하기 때문에 문제가 발생한다고 한다.
이를 해결하기 위해 MYSQL 5.5.3 부터 4바이트를 지원하는 utf8mb4라는 캐릭터 셋이 추가되었다.
그러므로 이모티콘을 지원하기 위해서는 테이블의 캐릭터 셋을 utf8에서 utf8mb4로 변경하면 된다.
Reference
https://hackernoon.com/today-i-learned-storing-emoji-to-mysql-with-golang-204a093454b7
'JS > Node.js' 카테고리의 다른 글
[Lambda] node-gyp (0) | 2019.05.16 |
---|---|
[정리] 아하 REST API 서버 개발 #3 (0) | 2019.03.31 |
[정리] 아하 REST API 서버 개발 #1, #2 (0) | 2019.03.31 |
[JS] require(), module.exports, exports
node.js 에서는 모듈을 불러오기 위해 require() 함수를 사용한다.
/*** a.js ***/
const a = 10;
module.exports = a;
/*** c.js ***/
const c = 10;
module.exports.c = c;
/*** d.js ***/
const d = 20;
/*** b.js ***/
const a = require('./a');
const c = require('./c');
const d = require('./d');
console.log(a); // 10
console.log(c); // { c: 10 }
console.log(d); // {}
실행결과는 주석의 내용과 같으며,
require()
를 통해 파일을 불러오면 해당 파일의module.exports
object 를 리턴한다는 것을 알 수 있다.
express
를 통해 라우터를 등록하는 기본형태를 확인해보자.
/*** routes/user.js ***/
const express = require('express');
const router = express.Router();
module.exports = router;
라우터의 기본 형태.
/*** app.js ***/
const express = require('express');
const userRouter = require('./routes/user');
const app = express();
app.use('/user', userRouter);
express
를 사용해서user
라우터를 등록하는 기본형태.
공식문서에서 아래와 같은 내용을 확인할 수 있다.
id
module name or path- Returns: exported module content
Used to import modules, JSON
, and local files. Modules can be imported from node_modules
. Local modules and JSON files can be imported using a relative path.
The module.exports
object is created by the Module
system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to module.exports
. Note that assigning the desired object to exports
will simply rebind the local exports
variable, which is probably not what is desired.
여기서 exports
라는 용어가 또 등장한다.
A reference to the module.exports
that is shorter to type. See the section about the exports shortcut for details on when to use exports
and when to use module.exports
.
module.exports.foo = "bar";
exports.foo = "bar";
이 두개는 같은 표현이다.
exports = {foo : "bar"};
하지만, 이렇게 할 경우 결과가 달라진다.
exports
라는 지역변수에{foo : "bar"}
라는 객체를 대입한 것이 되며, 이 경우module.exports
에 위의 내용이 포함되지 않게 된다.reference
가 아니게 되며, 별도의 변수로 인식이 되는 것 같다.
/*** a.js ***/
module.exports.a = 10;
exports.b = 20;
exports = { c : 30};
/*** b.js ***/
const a = require('./a');
console.log(a); // { a: 10, b: 20 }
module.exports.a = 10;
exports.b = 20;
console.log(exports); // { a: 10, b: 20 }
exports = { c : 30};
console.log(exports); // { c: 30 }
https://medium.com/@flsqja12_33844/require-exports-module-exports-공식문서로-이해하기-1d024ec5aca3
'JS > JS(ES6+)' 카테고리의 다른 글
[JS] import / export (0) | 2019.02.11 |
---|---|
[JS] 느낌표로 시작하는 함수 (0) | 2019.02.11 |
[JS] Symbol (ES6) (0) | 2019.01.20 |
[JS] Symbol (ES6)
자바스크립트에서 심볼이라는 것은 ES6에서 새로 추가된 7번째 타입.
Symbol(description)
과 같이 사용가능하며 유니크한 값을 리턴해준다.
description
자리는 문자열이 오며, 문자열을 직접 쓰거나, toString()
이 가능한 것들이 올 수 있다.
유니크한 값을 리턴하기 때문에 디스크립션이 같아도 다른 값이 된다.
const a = Symbol("hi");
const b = Symbol("hi");
console.log(a === b); // false
console.log(a); // Symbol(hi)
console.log(b); // Symbol(hi)
또한, 이처럼 어떤 값을 가지고 있는지 조회가 불가능하다.
유니크하지만 유일한 심볼을 만들 수 있다.
const c = Symbol.for("hi");
const d = Symbol.for("hi");
console.log(c === d); // true
console.log(a === c); // false
console.log(b === c); // false
심볼에 대해 알아보기 시작한 것은 FP 를 공부하면서, 아래의 코드가 이해가 되지 않아서부터였다.
const iterable = {
[Symbol.iterator]() {
let i = 3;
return {
next() {
return i==0 ? { done: true } : { value: i--, done: false }
}
}
}
}
사용자 정의 이터러블이다. 분명 객체이고, 그안에는 필드가 있어야 하는데, 필드의 형태가 이해가 되지 않았다.
ES6 에서 새로운 Object 를 정의하는 방법이 추가되어 그부분인가 싶었다. (Old object vs New object (ES6+))
var sayNode = function() {
console.log('Node');
};
var es = 'ES';
var oldObject = {
sayJS: function() {
console.log('JS');
},
sayNode: sayNode
};
oldObject[es + 6] = "Fantastic";
const newObject = {
sayJS() {
console.log('JS');
},
sayNode,
[es + 6]: "Fantastic"
};
newObject.sayNode(); // Node
newObject.sayJS(); // JS
console.log(newObjext.ES6); // Fantastic
문법이 짧아졌고, 값에서 function 을 쓰지 않아도 되며, key와 value 가 같은 경우, key 만 사용해도 된다.
변수가 들어가는 키의 경우 동적으로 객체를 변경해야 했으나, 이제는 객체 안에서 표현가능. 대괄호 이용.
좀 더 그룹화가 되었고, 타이핑 수를 절약할 수 있게 되었지만,
위의 사용자 정의 이터러블이라는 코드의 내용과는 뭔가가 다르다.
하지만, 아래의 예제를 보고 이해를 할 수 있었다.
const sb = Symbol('creator');
const obj = {
[sb]: 'zerocho',
a: 1,
b: 2,
};
console.log(obj.creator); // undefined
console.log(obj[Symbol('creator')]); // undefined
console.log(obj[sb]); // 'zerocho' (정확히 같은 Symbol 객체를 사용해야만 조회가능합니다.)
console.log(Object.keys(obj)); // [a, b] (심볼은 표시되지 않습니다)
console.log(obj); // { a: 1, b: 2, [Symbol(creator)]: 'zerocho' }
const a = Symbol("hi");
const obj = {};
obj[a] = "hello";
console.log(obj); // { [Symbol(hi)]: 'hello' }
위 두 예제에서처럼 심볼 프로퍼티는 [] 를 통해서만 접근이 가능하며, [] 통해 필드를 생성할 수 있다.
사용자 정의 이터러블을 다시 살펴보자.
const iterable = {
[Symbol.iterator]() {
let i = 3;
return {
next() {
return i==0 ? { done: true } : { value: i--, done: false }
}
}
}
}
위와 같이 되어 있다.
const iterable = {
[Symbol.iterator]: function() {
let i = 3;
return {
next() {
return i==0 ? { done: true } : { value: i--, done: false }
}
}
}
}
함수표현은 위와 같다고 생각할 수 있다.
그렇다면 Symbol.iterator
는..?
console.log(Symbol.iterator); // Symbol(Symbol.iterator)
위와 같이 디폴트로 할당된 심볼값임을 알 수 있다.
const s = Symbol('Symbol.iterator');
console.log(s); // Symbol(Symbol.iterator)
동일한 내용이 출력된다.
내가 내린 결론은?
Symbol.iterator = Symbol('Symbol.iterator');
내부적으로 위와 같이 구현이 되어있지 않을까 싶다.
https://www.zerocho.com/category/ECMAScript/post/58ef98a6177375001892f891
https://gist.github.com/qodot/ecf8d90ce291196817f8cf6117036997
'JS > JS(ES6+)' 카테고리의 다른 글
[JS] import / export (0) | 2019.02.11 |
---|---|
[JS] 느낌표로 시작하는 함수 (0) | 2019.02.11 |
[JS] require(), module.exports, exports (0) | 2019.01.25 |
[JS] 정규표현식을 이용한 str.replace() / pattern.exec()
- 여러 공백을 하나의 공백으로 바꾸는 정규표현식
- ref : https://code.i-harness.com/ko-kr/q/1e3ba5
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +/g, ' ' ) -> 380ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / +(?= )/g, ' ') -> 3250ms
- 문자열에서 모든 줄 바꿈(개행)을 제거하는 방버
- ref : https://code.i-harness.com/ko-kr/q/a4df85
someText = someText.replace(/(\r\n\t|\n|\r\t)/gm,"");
- 정규표현식을 사용하여 태그만 제거하기
- ref : https://webisfree.com/2015-12-22/[자바스크립트]-정규표현식을-사용하여-태그만-제거하기
var newText = oriText.replace(/(<([^>]+)>)/ig,"");
>> g : 발생할 모든 pattern에 대한 전역 검색
>> i : 대/소문자 구분 안함
>> ref : http://www.codejs.co.kr/자바스크립트에서-replace를-replaceall-처럼-사용하기/
- 특정 태그 추출
- ref: http://maedoop.dothome.co.kr/2231
- ref: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
'JS > Reference' 카테고리의 다른 글
How to make a Web Crawler in Node.js (0) | 2018.11.24 |
---|---|
How JS works (0) | 2018.10.02 |
이벤트 루프(Event Loop) (0) | 2018.10.02 |
How to make a Web Crawler in Node.js
1. How to make a web crawler in JavaScript / Node.js
http://www.netinstructions.com/how-to-make-a-simple-web-crawler-in-javascript-and-node-js/
2. “Introduction to Webcrawling (with Javascript and Node.js)” - “Introduction to Webcrawling (with Javascript and Node.js)” @DDCreationStudi
'JS > Reference' 카테고리의 다른 글
[JS] 정규표현식을 이용한 str.replace() / pattern.exec() (0) | 2018.12.26 |
---|---|
How JS works (0) | 2018.10.02 |
이벤트 루프(Event Loop) (0) | 2018.10.02 |