[{"content":"Optional chaining (?. 연산자) optional chaining 연산자 (?.) 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.\n?. 연산자는 . 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 nullish (en-US) (null 또는 undefined)이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.\n따라서 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식이 생성된다. 어떤 속성이 필요한지에 대한 보증이 확실하지 않는 경우 객체의 내용을 탐색하는 동안 도움이 될 수 있다.\noptional chaining은 선언되지 않은 루트 객체에 사용할 수 없지만, 정의되지 않은 루트 객체와는 함께 사용할 수 있다.\nconst adventurer = { name: \u0026#39;Alice\u0026#39;, cat: { name: \u0026#39;Dinah\u0026#39; } }; const dogName = adventurer.dog?.name; console.log(dogName); // expected output: undefined  console.log(adventurer.someNonExistentMethod?.()); // expected output: undefined 문법 obj?.prop obj?.[expr] arr?.[index] func?.(args) 설명 optional chaining 연산자는 참조나 기능이 undefined 또는 null일 수 있을 때 연결된 객체의 값에 접근하는 단순화할 수 있는 방법을 제공한다.\n예를 들어, 중첩된 구조를 가진 객체에서 obj가 있다. optional chaining이 없이 깊이 중첩된 하위 속성을 찾으려면, 다음과 같이 참조를 확인해야 한다:\nlet nestedProp = obj.first \u0026amp;\u0026amp; obj.first.second; obj.first의 값은 obj.first.second의 값에 접근하기 전에 null (그리고 undefined)가 아니라는 점을 검증한다. 이는 만약에 obj.first를 테스트 없이 obj.first.second 에 직접 접근할 때 일어날 수 있는 에러를 방지한다.\n그러나 optional chaining 연산자(?.)를 사용하여, obj.first.second 에 접근하기 전에 obj.first의 상태에 따라 명시적으로 테스트하거나 단락시키지 않아도 된다:\nlet nestedProp = obj.first?.second; . 대신에 ?. 연산자를 사용함으로써, 자바스크립트는 obj.first.second에 접근하기 전에 obj.first가 null 또는 undefined가 아니라는 것을 암묵적으로 확인하는 것을 알고 있다. 만약 obj.first가 null 또는 undefined이라면, 그 표현식은 자동으로 단락되어 undefined가 반환된다.\n이는 임시 변수가 실제로 생성되지 않는다는 점을 제외하고 다음과 동일하다.\nlet temp = obj.first; let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second); 함수의 호출과 Optional chaining 존재하지 않을 수 있는 매서드를 호출할 때, optional chaining을 사용할 수 있다. 예를 들어, 구현 기간이나 사용자 장치에서 사용할 수 없는 기능 때문에 메서드를 사용할 수 없는 API를 사용할 경우, 유용할 수 있다.\n함수 호출과 optional chaining을 사용함으로써 메서드를 찾을 수 없는 경우에 예외를 발생시키는 것 대신에 그 표현식은 자동으로 undefined를 반환한다:\nlet result = someInterface.customMethod?.(); 메모: 만약 속성에 해당 이름이 있지만 함수가 아니라면, ?.의 사용은 여전히 예외를 발생시킨다. TypeErrorexception (x.y`` is not a function).\n메모: 만약 someInterface 자체가 null이나 undefined이면, TypeError 예외가 여전히 발생 할 것이다. someInterface 자체가 null이나 undefined으로 예상된다면, ?.을 사용해야한다: someInterface?.customMethod?.()\noptional callbacks과 event handlers 다루기 만약 객체에서 destructuring assignment로 callbacks 또는 fetch 메서드를 사용한다면, 그 존재 여부를 테스트하지 않으면 함수로 호출할 수 없는 존재 하지 않는 값을 가질 수 있다. ?.을 사용하면, 다음 추가 테스트를 피할 수 있다:\n// Written as of ES2019 function doSomething(onContent, onError) { try { // ... do something with the data  } catch (err) { if (onError) { // Testing if onError really exists  onError(err.message); } } } // Using optional chaining with function calls function doSomething(onContent, onError) { try { // ... do something with the data  } catch (err) { onError?.(err.message); // no exception if onError is undefined  } } 표현식에서 Optional chaining optional chaining 연산자를 속성에 표현식으로 접근할 때 대괄호 표기법(the bracket notation of the property accessor)을 사용할 수 있다:\nlet nestedProp = obj?.[\u0026#39;prop\u0026#39; + \u0026#39;Name\u0026#39;]; Optional chaining은 할당자 왼쪽에서 유효하지 않습니다. let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment Optional chaining으로 배열 항목에 접근하기 let arrayItem = arr?.[42]; 예제 기본 예제 이 예제는 해당 멤버가 없을 때, map에서 멤버 bar의 name의 속성 값을 찾는다. 그러므로 결과는 undefined이다.\nlet myMap = new Map(); myMap.set(\u0026#34;foo\u0026#34;, {name: \u0026#34;baz\u0026#34;, desc: \u0026#34;inga\u0026#34;}); let nameBar = myMap.get(\u0026#34;bar\u0026#34;)?.name; 단락 평가 표현식에서 optional chaining을 사용할 때, 만약 왼쪽에 있는 피연산자가 null or undefined인 경우, 그 표현식은 평가되지 않는다. 예들 들어:\nlet potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; console.log(x); // 0 x는 증가하지 않음 optional chaining 연산자 쌓기 중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다:\nlet customer = { name: \u0026#34;Carl\u0026#34;, details: { age: 82, location: \u0026#34;Paradise Falls\u0026#34; // detailed address is unknown  } }; let customerCity = customer.details?.address?.city; // … this also works with optional chaining function call let duration = vacations.trip?.getTime?.(); 널 병합 연산자와 같이 사용하기 널 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다:\nlet customer = { name: \u0026#34;Carl\u0026#34;, details: { age: 82 } }; const customerCity = customer?.city ?? \u0026#34;Unknown city\u0026#34;; console.log(customerCity); // Unknown city ","permalink":"https://bynaki.github.io/posts/js.optional.chaining/","summary":"Optional chaining (?. 연산자) optional chaining 연산자 (?.) 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다.\n?. 연산자는 . 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 nullish (en-US) (null 또는 undefined)이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.\n따라서 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식이 생성된다.","title":"Js :: Optional chaining (?. 연산자)"},{"content":"JSDoc이란? JSDoc은 Javadoc과 유사한 JavaScript용 API 문서 생성기이다. 문서 주석을 코드와 함께 소스 코드에 직접 추가할 수 있다. JSDoc은 소스 코드를 스캔하고 HTML 문서를 생성한다.\nJSDoc의 주목적은 JavaScript 앱 또는 라이브러리 API를 문서화하는 것이다. 모듈, 네임스페이스, 클래스, 메서드, 파라미터 등과 같은 항목을 문서화할 것으로 가정한다.\n일반적으로 JSDoc 주석은 코드가 문서화되기 직전에 배치되어야 한다. 각 주석은 /** 시퀀스로 시작해야 JSDoc 파서가 인식할 수 있다. /*, /*** 으로 시작되는 설명은 무시된다.\nJSDoc을 사용해서 무엇을 할 수 있을까?   API 문서 생성\n가장 쉽게 생성하는 문서는 바로 API 문서이다. 프론트엔드 개발자가 서버에 어떤 데이터를 요청할 수 있고, 어떤 데이터를 응답받는지를 확인할 때 필수적으로 사용되는 것이 API 문서인데, 여기에는 기본적인 응답 요청 방식과 요청시 첨부되어야 하는 값 등이 기술된다.\n  타입 추론\n또한 함수의 반환값, 파라미터의 타입, 적절한 파라미터가 전달되지 않았을 때의 에러 메시지 등 다양한 내용을 주석으로 작성할 수 있기 때문에 TypeScript를 사용하는 것처럼 타입을 추론하고 디버깅을 쉽게 할 수 있다는 장점이 있다.\n  버그 픽스 리포트\n주석 분석기를 이용한 간단한 API 문서화 방법에서 소개한 방법처럼 버그 픽스 리포트로 사용할 수도 있겠다. 버전 별로 개선점 등을 작성하면 어떤 목적과 방향으로 개발이 진행되어 왔는지 한눈에 알 수 있을 것이다.\n  기본 사용법 /** foo 함수에 대한 주석을 여기에 작성한다 */ function foo() { } 특수 JSDoc 태그를 사용하면 더 많은 정보를 제공할 수 있고, 실제로 JSDoc을 사용하는 목적이 여기에 있다. 예를 들어 함수가 클래스의 생성자일 경우 @constructor 태그를 사용해 다음과 같이 작성할 수 있다.\n/** * Book 함수 * @constructor */ function Book(title, author) { } 이외에도 다양한 JSDoc 태그를 사용할 수 있다.\n/** * Book 함수 * @constructor * @param {string} title - The title of the book. * @param {string} author - The author of the book. */ function Book(title, author) { } Javadoc 가이트 템플릿을 참고해 다음과 같이 꼼꼼하게 주석을 작성할 수 있다.\n/** * 기본 작성 기준 * boolean 값이라면 언제 true이고 언제 false인지 작성 * 숫자라면 범위나 값의 의미를 작성 * enum이면 어떤 값을 쓸 수 있는지 나열 * 이 메서드를 호출하기 전후에 해야하는 작업이 있다면 해당 내용을 작성 * 특정 상황에서 이 메서드를 사용하지 않아야 한다면 해당 내용을 작성 * @global 전역에 해당하는 내용을 작성 * @function 어떤 파라미터를 받아서 어떤 값을 반환하는 함수인지 작성 * @param 어떤 타입의 파라미터를 전달해야 하는지 작성 * 허락되지 않은 파라미터를 전달했을 때 어떤 일이 발생하는지 작성 * @return 무엇을 반환해야 하는지 작성 * 문제가 발생했을 때 일반 상황과 다른 의미의 값을 반환한다면 해당 내용을 작성 * @callback 전역인지 지역인지 구분 및 어떤 함수인지 작성 * @event 어떤 이벤트인지 작성 */ 각 소스 코드에 맞는 JSDoc 태그의 사용법은 https://jsdoc.app/ 에서 확인하자.\nJSDoc 사용해보기 이제 JSDoc을 직접 사용해보자. 간단하게 사칙연산에 대한 문서를 작성하려고 한다.\nJSDoc을 테스트 해 볼 새로운 폴더를 생성해 기본 환경 세팅한다.\n$ mkdir test-jsdoc \u0026amp;\u0026amp; cd test-jsdoc $ npm init -y $ touch index.js $ npm i -d jsdoc 여기까지 하면 JSDoc을 사용하기 위한 준비를 마쳤다.\n이제 루트 위치에 있는 index.js 파일에 덧셈을 하는 함수에 대한 주석을 작성해보자.\n/** @function addition * @param {number} a 연산하고자 하는 0 이상의 정수 * @param {number} b 연산하고자 하는 0 이상의 정수 * @returns {number} a + b */ const addition = (a, b) =\u0026gt; a + b; 문서화 하기 이제 작성한 주석을 확인해야 한다. 터미널에서 다음 명령어를 입력한다.\n$ ./node_modules/.bin/jsdoc index.js 명령어가 굉장히 긴데, webpack을 사용해 npm 명령어를 사용하는 방법이 하단에 소개되어 있다. 다만 로컬로 JSDoc을 설치하지 않고 다음과 같이 전역으로 설치했다면\n$ npm install -g jsdoc 컴파일할 때 좀 더 간편한 명령어를 사용할 수 있다.\n$ jsdoc ./index.js 다만 여기서는 로컬에 설치했다고 가정하고 엄청나게 긴 명령어 ./node_modules/.bin/jsdoc index.js를 입력해보자.\n그러면 다음과 같이 out 폴더가 생성된다.\n생성된 out 폴더 내부에 있는 index.html을 열면 문서화 된 주석 내용을 확인할 수 있다.\nindex.js에 작성했던 addition 함수에 관한 주석이 생성된 것이 보인다.\n이번에는 뺄셈에 관한 함수를 추가해보자.\n/** * a는 b보다 크거나 같다 * a가 b보다 적은 수라면 -1을 반환한다 * @function subtraction * @param {number} a 연산하고자 하는 0 이상의 정수 * @param {number} b 연산하고자 하는 0 이상의 정수 * @returns {number} a - b */ const subtraction = (a, b) =\u0026gt; a \u0026gt;= b ? a - b : -1; 그러면 문서는 다음과 같이 작성된다. Global 아래 addition 함수와 subtraction 함수가 나열된다.\n우측의 메뉴를 누르면 해당 함수 위치로 이동한다.\n구분된 폴더 내부의 .js 모두 문서화하기 만약 모든 함수를 루트 위치에 있는 index.js에 작성하지 않고 src 폴더를 만들어 폴더 내부의 .js 파일에 작성하면 어떻게 문서가 만들어질까? 그래서 이번에는 src 폴더를 만들고 폴더 내부에 test.js 라는 파일을 만들어 곱셈에 대한 함수를 작성해보았다.\n/** @function multiplication * @param {number} a 연산하고자 하는 0 이상의 정수 * @param {number} b 연산하고자 하는 0 이상의 정수 * @returns {number} a * b */ const multiplication = (a, b) =\u0026gt; a * b; 작성한 주석을 확인해보자.\n./node_modules/.bin/jsdoc src/test.js 이미 문서로 만들어진 index.js는 그대로 존재하고 거기에 곱셈에 관한 함수가 추가될 거라고 생각했는데 실제로는 기존에 작성했던 주석이 사라지고 방금 작성한 주석만 남아있다.\n경로를 직접 입력하며 문서를 만드는 경우에는 다음과 같이 모든 경로를 다 써줘야 처음에 생각했던 대로 모든 문서가 합쳐진 하나의 문서가 만들어진다.\n./node_modules/.bin/jsdoc index.js src/test.js 이 방법은 너무 번거롭고 효율적이지도 못하기 때문에 폴더 내부의 모든 js, jsx, jsdoc 확장자를 가진 파일이 한꺼번에 동작할 수 있도록 설정 파일을 수정해보자.\n설정 파일을 수정해 JSDoc 편리하게 사용하기 루트 위치에 jsdoc.config.json 이라는 이름을 가진 파일을 하나 생성한다. 그리고 위에서 언급한 확장자를 가진 파일을 모두 문서로 만들어줄 수 있도록 객체를 만들어주자.\n기본 설정 기본 공식 문서에 나와있는 기본 설정값은 다음과 같다.\n{ \u0026#34;plugins\u0026#34;: [], \u0026#34;recurseDepth\u0026#34;: 10, \u0026#34;source\u0026#34;: { \u0026#34;includePattern\u0026#34;: \u0026#34;.+\\\\.js(doc|x)?$\u0026#34;, \u0026#34;excludePattern\u0026#34;: \u0026#34;(^|\\\\/|\\\\\\\\)_\u0026#34; }, \u0026#34;sourceType\u0026#34;: \u0026#34;module\u0026#34;, \u0026#34;tags\u0026#34;: { \u0026#34;allowUnknownTags\u0026#34;: true, \u0026#34;dictionaries\u0026#34;: [\u0026#34;jsdoc\u0026#34;,\u0026#34;closure\u0026#34;] }, \u0026#34;templates\u0026#34;: { \u0026#34;cleverLinks\u0026#34;: false, \u0026#34;monospaceLinks\u0026#34;: false } }  plugins: 플러그인 사용시 추가하는 부분. 기본값은 빈 상태이다. recurseDepth: -r 명령 행 플래그로 재귀를 사용하면 JSDoc은 10 레벨 깊이의 파일을 검색한다. source.includePattern: js, jsx, jsdoc으로 끝나는 파일만 처리한다. source.excludePattern: 밑줄로 시작하거나 밑줄로 시작하는 디렉토리의 모든 파일은 무시한다. sourceType: ES2015 모듈을 사용하는 코드를 지원한다. tags.allowUnknownTags: JSDoc에서 인식할 수 없는 태그를 사용할 수 있다. tags.dictionaries: 표준 JSDoc 태그와 Closure Compiler 태그가 모두 활성화 된다. templates.cleverLinks, templates.monospaceLinks: 인라인 {@link} 태그는 일반 텍스트로 렌더링 된다.  기본 설정을 입력하고, 이 설정대로 문서를 만드는 명령어는 다음과 같다.\n./node_modules/.bin/jsdoc -c jsdoc.config.json . 이렇게 문서를 만들면 아래와 같은 문서가 만들어진다.\nsrc 폴더에 만들었던 multiplication 함수에 대한 문서가 사라졌다. 폴더가 구분이 되어있어서 발생하는 문제인데, 루트 위치가 아닌 폴더에 있는 js 파일에 대한 문서화도 함께 진행하려면 설정값을 조금 수정해야 한다.\n폴더 내부 파일 문서화 지원 설정 source 객체 내부에 \u0026quot;include\u0026quot;: [\u0026quot;폴더명\u0026quot;], 를 추가해준다. 배열이기 때문에 루트 위치와 특정 폴더 위치를 모두 삽입해준다. source 객체는 다음과 같은 형태로 구성된다.\n\u0026#34;source\u0026#34;: { \u0026#34;include\u0026#34;: [\u0026#34;.\u0026#34;, \u0026#34;src\u0026#34;], \u0026#34;includePattern\u0026#34;: \u0026#34;.+\\\\.js(doc|x)?$\u0026#34;, \u0026#34;excludePattern\u0026#34;: \u0026#34;(^|\\\\/|\\\\\\\\)_\u0026#34; }, 설정 값을 수정하고 다시 문서를 만들면 의도했던 대로 모든 .js 파일을 문서로 확인할 수 있다!\nREADME.md 추가하기 문서화는 완료됐는데 문서로 진입하기 전 메인 화면이 텅 비어있으니 너무 썰렁하다. 여기에 README.md를 추가해서 문서에 관한 간단한 설명을 작성해보자. 루트 위치에 README.md를 생성하고 다음과 같이 작성한다.\n# 사칙연산 문서 ## [addition](global.html#addition)  ## [subtraction](global.html#subtraction)  ## [multiplication](global.html#multiplication) 이제 JSDoc이 md 파일을 인식할 수 있도록 해야 한다. 설정으로 돌아가 plugins와 opts를 아래와 같이 변경한다.\n\u0026#34;plugins\u0026#34;: [ \u0026#34;plugins/markdown\u0026#34; ], \u0026#34;opts\u0026#34;: { \u0026#34;readme\u0026#34;: \u0026#34;README.md\u0026#34; } 설정값을 변경한 후 문서를 만들면 아래와 같이 메인 화면이 변경된다.\n링크를 클릭하면 해당 함수의 설명 위치로 가는 README.md 파일이 생성되었다!\n추가로 Docs에서 한글을 사용하는데 무리가 없도록 인코딩 설정을 수정하면 기본적인 설정은 완료된다.\n\u0026#34;opts\u0026#34;: { \u0026#34;encoding\u0026#34;: \u0026#34;utf8\u0026#34;, \u0026#34;readme\u0026#34;: \u0026#34;README.md\u0026#34; } webpack으로 문서화 명령어 변경하기 지금까지는 매번 ./node_modules/.bin/jsdoc -c jsdoc.config.json . 명령어를 사용해서 문서화를 했다. 이것도 설정 파일을 만들기 전에는 index.js, src/test.js 하는 식으로 직접 경로까지 지정해줬어야 했는데 설정 파일을 만들면서 .js 파일을 몇 개를 더 만들든 같은 명령어로 동작할 수 있게 되었다.\n하지만 조금 개선됐다고 하더라도 컴파일 명령어 자체가 너무 길고 파일에 변화가 있을 때마다 매번 이렇게 긴 명령어를 입력해야 한다는 단점이 있다. 이걸 좀 더 간단한 명령어를 사용할 수는 없을까? webpack을 사용하면 이런 문제를 해결할 수 있다.\n먼저 webpack과 jsdoc-webpack-plugin을 설치하자.\n$ npm i -d webpack webpack-cli jsdoc-webpack-plugin 설치가 완료됐으면 루트 위치에 webpack.config.js 파일을 생성해 webpack에 대한 설정을 한다.\nconst path = require(\u0026#34;path\u0026#34;); const JsDocPlugin = require(\u0026#34;jsdoc-webpack-plugin\u0026#34;); module.exports = { entry: \u0026#34;./index.js\u0026#34;, output: { path: path.join(__dirname, \u0026#34;dist\u0026#34;), filename: \u0026#34;main.js\u0026#34; }, plugins: [ new JsDocPlugin({ conf: \u0026#34;jsdoc.config.json\u0026#34;, cwd: \u0026#34;.\u0026#34;, preserveTmpFile: false }) ] }; 그리고 package.json 파일에서 start 명령어를 추가해준다.\n\u0026#34;scripts\u0026#34;: { \u0026#34;start\u0026#34;: \u0026#34;webpack\u0026#34; }, 이제 npm start 라고 명령어를 입력하면 문서화 작업을 진행할 수 있다.\n 참고\n JSDoc 3.5 (한국어) Javascript Documentation 라이브러리 JSDoc를 사용해 봅시다 주석 분석기를 이용한 간단한 API 문서화 방법  ","permalink":"https://bynaki.github.io/posts/js.jsdoc/","summary":"JSDoc이란? JSDoc은 Javadoc과 유사한 JavaScript용 API 문서 생성기이다. 문서 주석을 코드와 함께 소스 코드에 직접 추가할 수 있다. JSDoc은 소스 코드를 스캔하고 HTML 문서를 생성한다.\nJSDoc의 주목적은 JavaScript 앱 또는 라이브러리 API를 문서화하는 것이다. 모듈, 네임스페이스, 클래스, 메서드, 파라미터 등과 같은 항목을 문서화할 것으로 가정한다.\n일반적으로 JSDoc 주석은 코드가 문서화되기 직전에 배치되어야 한다. 각 주석은 /** 시퀀스로 시작해야 JSDoc 파서가 인식할 수 있다. /*, /*** 으로 시작되는 설명은 무시된다.\nJSDoc을 사용해서 무엇을 할 수 있을까?","title":"Js :: JsDoc"},{"content":"async function을 바로 return하면 error를 catch 하지 못한다.\nlet count = 0 function asyncFunc() { return new Promise((resolve, reject) =\u0026gt; { if(count % 10 === 0) { count++ reject(new Error(\u0026#39;error!!\u0026#39;)) return } resolve(++count) }) } async function bad() { try { // await 하지 않고 바로 리턴하면 에러를 캣치하지 못한다.  return asyncFunc() } catch(e) { console.log(e.message) return asyncFunc() } } async function right() { try { const res = await asyncFunc() return res } catch(e) { console.log(e.message) return asyncFunc() } } test(\u0026#39;test async reject\u0026#39;, async t =\u0026gt; { for(let i = 0; i \u0026lt; 100; i++) { const res = await right() console.log(res) } t.pass() }) error!! 2 3 4 5 6 7 8 9 10 error!! 12 . . . 110 error!! 112 ","permalink":"https://bynaki.github.io/posts/js.async-await-catch-error/","summary":"async function을 바로 return하면 error를 catch 하지 못한다.\nlet count = 0 function asyncFunc() { return new Promise((resolve, reject) =\u0026gt; { if(count % 10 === 0) { count++ reject(new Error(\u0026#39;error!!\u0026#39;)) return } resolve(++count) }) } async function bad() { try { // await 하지 않고 바로 리턴하면 에러를 캣치하지 못한다.  return asyncFunc() } catch(e) { console.log(e.message) return asyncFunc() } } async function right() { try { const res = await asyncFunc() return res } catch(e) { console.","title":"Js :: async/await Catch Error"},{"content":"while writing go this morning, I found that the wrong code are not under lined by red line This is really difficult for me and time consuming to keep writing. After 1 hour of wasting time trying to figure out what happened, I decide to kill it all and start again. Hope this will be helpful for those who wants to complete remove vscode on their mac\nATTENTION please write down your extension lists, and settings (JSON) because you won’t be seeing this anymore (screen shot?)\n remember to quit vscode first\n Step1 remove settings and configs\nrm -rf $HOME/Library/Application\\ Support/Code // add sudo if you needed to// if you\u0026#39;re using insider* sudo rm -rf $HOME/Library/Application\\ Support/Code\\ -\\ Insiders/ Step2 remove all the extensions\nrm -rf $HOME/.vscode // add sudo if you needed to// if you\u0026#39;re using insider* sudo rm -rf $HOME/.vscode-insiders/ Step3 remove vscode from application\nStep4 download vscode and install again ;)\n","permalink":"https://bynaki.github.io/posts/vscode.complete-uninstall/","summary":"while writing go this morning, I found that the wrong code are not under lined by red line This is really difficult for me and time consuming to keep writing. After 1 hour of wasting time trying to figure out what happened, I decide to kill it all and start again. Hope this will be helpful for those who wants to complete remove vscode on their mac\nATTENTION please write down your extension lists, and settings (JSON) because you won’t be seeing this anymore (screen shot?","title":"Vscode :: Complete uninstall / remove vscode (Mac)"},{"content":"for await\u0026hellip;of for await...of 구문은 보통 비동기에 대응하는 열거자를 나열할 때 쓰이지만, String, Array, Array 같은 객체 (e.g., arguments or NodeList), TypedArray, Map, Set 같은 동기적으로 열거 가능한 객체 또한 가능하며, 사용자가 직접 정의한 동기 또는 비동기 객체도 나열할 수 있도록 해준다. 일반적인 for ...of 문과 마찬가지로 열거자 심볼이 정의한 속성을 실행하게 되어 열거한 값을 변수로 받아 처리한다.\n구문 for await (variable of iterable) { statement }   variable\n열거할 때마다 variable. 문을 통해 변수로 받을 수 있다. variable 문 안에서는 const, let 및 var. 문으로 선언된 변수 및 상수를 선언할 수 있다.\n  iterable\n열거 가능한 속성이 들어가 있는 객체 및 식을 포함한다.\n  비동기 열거 속성을 통한 열거 식 비동기 열거 프로토콜을 담은 객체를 아래와 같이 열거할 수 있다.\nconst asyncIterable = { [Symbol.asyncIterator]() { return { i: 0, next() { if (this.i \u0026lt; 3) { return Promise.resolve({ value: this.i++, done: false }); } return Promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asyncIterable) { console.log(num); } })(); // 0 // 1 // 2 비동기 생성자를 통한 열거 식 비동기 생성자는 애초부터 비동기 열거 프로토콜을 탑재한 채로 정의한다.이를 for await...of 식으로 아래와 같이 사용할 수 있다.\nasync function* asyncGenerator() { let i = 0; while (i \u0026lt; 3) { yield i++; } } (async function() { for await (let num of asyncGenerator()) { console.log(num); } })(); // 0 // 1 // 2 좀 더 상세한 비동기 생성자를 통한 for await...of 식의 사용법을 위해 기본 API를 통해 값을 비동기적으로 열거하는 방법을 알아본다.\n아래 예제를 통해 먼저 API를 사용하여 스트림 데이터를 통해 비동기 열거자를 만든 뒤, 스트림에서 응답이 끝나면 최종 응답 데이터 크기를 가져온다.\nasync function* streamAsyncIterator(stream) { const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaseLock(); } } // 주소로부터 데이터를 받아온 뒤, 응답 크기를 구하는 비동기 생성자 함수. async function getResponseSize(url) { const response = await fetch(url); // 여기에 응답 크기를 바이트 단위로 적재한다.  let responseSize = 0; // for-await-of 문을 통해 응답이 들어올 때마다 열거 프로토콜을 통해 반복문이 작동한다.  for await (const chunk of streamAsyncIterator(response.body)) { // 총 응답 크기를 지속적으로 누적한다.  responseSize += chunk.length; } console.log(`응답 크기: ${responseSize}바이트`); // 예상 출력: \u0026#34;응답 크기: 1071472 바이트\u0026#34;  return responseSize; } getResponseSize(\u0026#39;https://jsonplaceholder.typicode.com/photos\u0026#39;); My Example export class TradeDb { constructor(private readonly filename: string) { } // *  // *  // *  async * each(code: string): AsyncGenerator\u0026lt;Iu.TradeTickType, void, unknown\u0026gt; { const length = 500 let offset = 0 let trs = [] do { trs = await this.get(code, offset, length) for(let tr of trs) { yield tr } offset += trs.length } while(trs.length !== 0) } } export class UPbitTradeMock extends BaseUPbitSocket { constructor(private readonly db: TradeDb) { super(db.staticCodes()) } async open(): Promise\u0026lt;void\u0026gt; { await this.start() const codes = await this.db.codes() for(let code of codes) { const bots = this.getBots(I.ReqType.Trade, code) for await (let tr of this.db.each(code)) { const converted = this.convertTradeType(tr) await Promise.all(bots.map(bot =\u0026gt; bot.trigger(converted))) } await Promise.all(bots.map(bot =\u0026gt; bot.finish())) } } } See Also  https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/for-await...of  ","permalink":"https://bynaki.github.io/posts/js.for-wait-of/","summary":"for await\u0026hellip;of for await...of 구문은 보통 비동기에 대응하는 열거자를 나열할 때 쓰이지만, String, Array, Array 같은 객체 (e.g., arguments or NodeList), TypedArray, Map, Set 같은 동기적으로 열거 가능한 객체 또한 가능하며, 사용자가 직접 정의한 동기 또는 비동기 객체도 나열할 수 있도록 해준다. 일반적인 for ...of 문과 마찬가지로 열거자 심볼이 정의한 속성을 실행하게 되어 열거한 값을 변수로 받아 처리한다.\n구문 for await (variable of iterable) { statement }   variable","title":"Js :: for wait...of"},{"content":"Promise.all() source:\nconst times = [2000, 500, 3000, 1000] await Promise.all(times.map(async t =\u0026gt; { await stop(t) console.log(t) })) output:\n500 1000 2000 3000 ","permalink":"https://bynaki.github.io/posts/js.promise-all/","summary":"Promise.all() source:\nconst times = [2000, 500, 3000, 1000] await Promise.all(times.map(async t =\u0026gt; { await stop(t) console.log(t) })) output:\n500 1000 2000 3000 ","title":"Js :: Promise.all()"},{"content":"Usage NVM To download, compile, and install the latest release of node, do this:\nnvm install node # \u0026#34;node\u0026#34; is an alias for the latest version To install a specific version of node:\nnvm install 6.14.4 # or 10.10.0, 8.9.1, etc The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).\nYou can list available versions using ls-remote:\nnvm ls-remote And then in any new shell just use the installed version:\nnvm use node Or you can just run it:\nnvm run node --version Or, you can run any arbitrary command in a subshell with the desired version of node:\nnvm exec 4.2 node --version You can also get the path to the executable to where it was installed:\nnvm which 5.0 ","permalink":"https://bynaki.github.io/posts/node.usage-nvm/","summary":"Usage NVM To download, compile, and install the latest release of node, do this:\nnvm install node # \u0026#34;node\u0026#34; is an alias for the latest version To install a specific version of node:\nnvm install 6.14.4 # or 10.10.0, 8.9.1, etc The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).\nYou can list available versions using ls-remote:\nnvm ls-remote And then in any new shell just use the installed version:","title":"Node :: Usage nvm"},{"content":"Generator **Generator** 객체는 generator function 으로부터 반환된 값이며 반복자와 반복자 프로토콜을 준수합니다.\n문법 function* gen() { yield 1; yield 2; yield 3; } var g = gen(); // \u0026#34;Generator { }\u0026#34; 메서드   Generator.prototype.next()\nyield 표현을 통해 yield된 값을 반환합니다.\n  Generator.prototype.return()\n주어진 값을 반환하고 생성기를 종료합니다.\n  Generator.prototype.throw()\n생성기로 에러를 throw합니다.\n  예시 무한 반복자 function* idMaker(){ var index = 0; while(true) yield index++; } var gen = idMaker(); // \u0026#34;Generator { }\u0026#34;  console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 // ... See Also  https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Generator  ","permalink":"https://bynaki.github.io/posts/js.generator/","summary":"Generator **Generator** 객체는 generator function 으로부터 반환된 값이며 반복자와 반복자 프로토콜을 준수합니다.\n문법 function* gen() { yield 1; yield 2; yield 3; } var g = gen(); // \u0026#34;Generator { }\u0026#34; 메서드   Generator.prototype.next()\nyield 표현을 통해 yield된 값을 반환합니다.\n  Generator.prototype.return()\n주어진 값을 반환하고 생성기를 종료합니다.\n  Generator.prototype.throw()\n생성기로 에러를 throw합니다.\n  예시 무한 반복자 function* idMaker(){ var index = 0; while(true) yield index++; } var gen = idMaker(); // \u0026#34;Generator { }\u0026#34;  console.","title":"Js :: Generator"},{"content":"Summary: in this tutorial, you will learn how to delete data in the SQLite database from a Node.js application.\nTo delete data in the SQLite database from a Node.js application, you use the following steps:\n Open a database connection. Execute a DELETE statement. Close the database connection.  For the demonstration, we will use the langs table in the sample.db database that we created in the previous tutorial.\nDeleting data example To delete data from a table, you use the DELETE statement as follows:\nDELETE FROM table_name WHERE column_name = value; To execute the DELETE statement from a Node.js application, you call the run() method of the Database object as follows:\ndb.run(sql, params, function(err) { // }); The run() method allows you to execute a DELETE statement with specified parameters and calls a callback function afterwards.\nIf there was any error during the execution of DELETE statement, the err argument of the callback function will provide the detail. In case the DELETE statement executed successfully, the this object of the callback function will contain the changes property that stores the number of rows deleted.\nThe following delete.js program illustrates how to delete a row from the langs table:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open a database connection let db = new sqlite3.Database(\u0026#39;./db/sample.db\u0026#39;, (err) =\u0026gt; { if (err) { console.error(err.message); } }); let id = 1; // delete a row based on id db.run(`DELETE FROM langs WHERE rowid=?`, id, function(err) { if (err) { return console.error(err.message); } console.log(`Row(s) deleted ${this.changes}`); }); // close the database connection db.close((err) =\u0026gt; { if (err) { return console.error(err.message); } }); Let’s test the update.js program.\n\u0026gt;node delete.js Row(s) deleted: 1 The output showed that one row has been deleted successfully.\nIn this tutorial, you have learned how to delete data in the SQLite database from a Node.js application.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.delete-sqlite/","summary":"Summary: in this tutorial, you will learn how to delete data in the SQLite database from a Node.js application.\nTo delete data in the SQLite database from a Node.js application, you use the following steps:\n Open a database connection. Execute a DELETE statement. Close the database connection.  For the demonstration, we will use the langs table in the sample.db database that we created in the previous tutorial.\nDeleting data example To delete data from a table, you use the DELETE statement as follows:","title":"Node :: Deleting Data in SQLite Database from a Node.js Application"},{"content":"Summary: this tutorial shows you how to update data in the SQLite database from a Node.js application.\nTo update data in the SQLite database from a Node.js application, you use these steps:\n Open a database connection. Execute an UPDATE statement. Close the database connection.  For the demonstration, we will use the langs table in the sample.db database that we created in the previous tutorial.\nUpdating data example To update data in a table, you use the UPDATE statement as follows:\nUPDATE table_name SET column_name = value_1 WHERE id = id_value; To execute the UPDATE statement in the Node.js application, you call the run() method of the Database object:\ndb.run(sql, params, function(err){ // }); The run() method executes an UPDATE statement with specified parameters and calls a callback afterwards.\nThe err argument of the callback stores the error detail in case the execution has any problem e.g., syntax error, locking, etc.\nIf the UPDATE statement is executed successfully, the this object of the callback function will contain the changes property that stores the number of rows updated.\nThe following update.js program illustrates how to update a row in the langs table from C to Ansi C:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open a database connection let db = new sqlite3.Database(\u0026#39;./db/sample.db\u0026#39;); // let data = [\u0026#39;Ansi C\u0026#39;, \u0026#39;C\u0026#39;]; let sql = `UPDATE langs SET name = ? WHERE name = ?`; db.run(sql, data, function(err) { if (err) { return console.error(err.message); } console.log(`Row(s) updated: ${this.changes}`); }); // close the database connection db.close(); Let’s test the update.js program.\n\u0026gt;node update.js Row(s) updated: 1 The output showed that one row has been updated which is correct.\nIn this tutorial, you have learned how to update data in the SQLite database from a Node.js application.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.update-sqlite/","summary":"Summary: this tutorial shows you how to update data in the SQLite database from a Node.js application.\nTo update data in the SQLite database from a Node.js application, you use these steps:\n Open a database connection. Execute an UPDATE statement. Close the database connection.  For the demonstration, we will use the langs table in the sample.db database that we created in the previous tutorial.\nUpdating data example To update data in a table, you use the UPDATE statement as follows:","title":"Node :: Updating Data in SQLite Database from a Node.js Application"},{"content":"Summary: in this tutorial, you will learn how to insert one or more row into an SQLite table from a Node.js application.\nTo insert data into an SQLite table from a Node.js application, you follow these steps:\n Open a database connection. Execute an INSERT statement. Close the database connection.  For the demonstration, we will create a new database named sample.db in the db folder.\nWhen you open a database connection in the default mode, the database is created if it does not exist.\nlet db = new sqlite3.Database(\u0026#39;./db/sample.db\u0026#39;); In the sample.db database, we create a table called langs for storing programming languages:\ndb.run(\u0026#39;CREATE TABLE langs(name text)\u0026#39;); You can run the program to create the sample.db database and langs table as follows:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); let db = new sqlite3.Database(\u0026#39;../db/sample.db\u0026#39;); db.run(\u0026#39;CREATE TABLE langs(name text)\u0026#39;); db.close(); Now, we are ready to insert data into the langs table.\nInsert one row into a table To execute an INSERT statement, you use the run() method of the Database object:\ndb.run(sql, params, function(err){ // }); The run() method executes an INSERT statement with specified parameters and calls a callback afterwards.\nIf an error occurred, you can find the detailed information in the err argument of the callback function.\nIn case the statement is executed successfully, the this object of the callback function will contain two properties:\n lastID property stores the value of the last inserted row ID. changes property stores the rows affected by the query.  The following insert.js program illustrates how to insert a row into the langs table:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); let db = new sqlite3.Database(\u0026#39;./db/sample.db\u0026#39;); // insert one row into the langs table  db.run(`INSERT INTO langs(name) VALUES(?)`, [\u0026#39;C\u0026#39;], function(err) { if (err) { return console.log(err.message); } // get the last insert id  console.log(`A row has been inserted with rowid ${this.lastID}`); }); // close the database connection  db.close(); Let’s run the insert.js program:\n\u0026gt;node insert.js A row has been inserted with rowid 1 It worked as expected.\nInsert multiple rows into a table at a time To insert multiple rows at a time into a table, you use the following form of the INSERT statement:\nINSERT INTO table_name(column_name) VALUES(value_1), (value_2), (value_3),... To simulate this in the Node.js application, we first need to construct the INSERT statement with multiple placeholders:\nINSERT INTO table_name(column_name) VALUES(?), (?), (?),... Suppose, you want to insert rows into the langs table with the data from the following languages array:\nlet languages = [\u0026#39;C++\u0026#39;, \u0026#39;Python\u0026#39;, \u0026#39;Java\u0026#39;, \u0026#39;C#\u0026#39;, \u0026#39;Go\u0026#39;]; To construct the INSERT statement, we use the map() method to map each element in the languages array into (?) and then join all placeholders together.\nlet placeholders = languages.map((language) =\u0026gt; \u0026#39;(?)\u0026#39;).join(\u0026#39;,\u0026#39;); let sql = \u0026#39;INSERT INTO langs(name) VALUES \u0026#39; + placeholders; The following insert-many.js program illustrates how to insert multiple rows into the langstable:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database connection let db = new sqlite3.Database(\u0026#39;../db/sample.db\u0026#39;); let languages = [\u0026#39;C++\u0026#39;, \u0026#39;Python\u0026#39;, \u0026#39;Java\u0026#39;, \u0026#39;C#\u0026#39;, \u0026#39;Go\u0026#39;]; // construct the insert statement with multiple placeholders // based on the number of rows let placeholders = languages.map((language) =\u0026gt; \u0026#39;(?)\u0026#39;).join(\u0026#39;,\u0026#39;); let sql = \u0026#39;INSERT INTO langs(name) VALUES \u0026#39; + placeholders; // output the INSERT statement console.log(sql); db.run(sql, languages, function(err) { if (err) { return console.error(err.message); } console.log(`Rows inserted ${this.changes}`); }); // close the database connection db.close(); Let’s run the insert-many.js program to see how it works.\n\u0026gt; node insert-many.js INSERT INTO langs(name) VALUES (?),(?),(?),(?),(?) Rows inserted 5 It inserted 5 rows into the langs table which is what we expected.\nIn this tutorial, you have learned how to insert one or more rows into an SQLite table from a Node.js application.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.insert-sqlite/","summary":"Summary: in this tutorial, you will learn how to insert one or more row into an SQLite table from a Node.js application.\nTo insert data into an SQLite table from a Node.js application, you follow these steps:\n Open a database connection. Execute an INSERT statement. Close the database connection.  For the demonstration, we will create a new database named sample.db in the db folder.\nWhen you open a database connection in the default mode, the database is created if it does not exist.","title":"Node :: Inserting Data Into an SQLite Table from a Node.js Application"},{"content":"Summary: in this tutorial, you will learn how to control the execution flow of statements.\nThe sqlite3 module provides you with two methods for controlling the execution flow of statements. The serialize() method allows you to execute statements in serialized mode, while the parallelize() method executes the statements in parallel.\nLet’s look into each method in detail to understand how it works.\nExecuting statement in serialized mode with Database.serialize The serialize() method puts the execution mode into serialized mode. It means that only one statement can execute at a time. Other statements will wait in a queue until all the previous statements are executed.\nAfter the serialize() method returns, the execution mode is set to the original mode again.\nIt’s safe to nest the serialize() method as follows:\ndb.serialize(() =\u0026gt; { // queries will execute in serialized mode  db.serialize(() =\u0026gt; { // queries will execute in serialized mode  }); // queries will execute in serialized mode }); Suppose, you want to execute the following three statements in sequence:\n Create a new table. Insert data into the table. Query data from the table.  To do this, you place these statements in the serialize() method as follows:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database connection let db = new sqlite3.Database(\u0026#39;:memory:\u0026#39;, (err) =\u0026gt; { if (err) { console.error(err.message); } }); db.serialize(() =\u0026gt; { // Queries scheduled here will be serialized.  db.run(\u0026#39;CREATE TABLE greetings(message text)\u0026#39;) .run(`INSERT INTO greetings(message) VALUES(\u0026#39;Hi\u0026#39;), (\u0026#39;Hello\u0026#39;), (\u0026#39;Welcome\u0026#39;)`) .each(`SELECT message FROM greetings`, (err, row) =\u0026gt; { if (err){ throw err; } console.log(row.message); }); }); // close the database connection db.close((err) =\u0026gt; { if (err) { return console.error(err.message); } }); Because the run() method returns a Database object so that we could chain the method calls.\nLet’s run the program to see how it works.\n\u0026gt; node serialize.js Hi Hello Welcome It works as expected.\nNotice that if you don’t place three statements in the serialize() method, all the three statements may execute in parallel which would cause an error.\nExecuting statements in parallel with Database.parallelize If you want the scheduled queries to execute in parallel, you place them in the parallelize()method.\nSimilar to the serialize() method, it is safe to nest the parallelize() method as follows:\ndb.parallelize(() =\u0026gt; { // queries will execute in parallel mode  db.parallelize(() =\u0026gt; { // queries will execute in parallel mode  }); // queries will execute in parallel mode }); For the demonstration, we will create a new function that calculates the sum of two numbers using SQLite database and place the function calls in the parallelize() method as shown in the following example:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open a database connection let db = new sqlite3.Database(\u0026#39;:memory:\u0026#39;, (err) =\u0026gt; { if (err) { console.error(err.message); } }); db.parallelize(() =\u0026gt; { dbSum(1, 1, db); dbSum(2, 2, db); dbSum(3, 3, db); dbSum(4, 4, db); dbSum(5, 5, db); }); // close the database connection db.close((err) =\u0026gt; { if (err) { return console.error(err.message); } }); function dbSum(a, b, db) { db.get(\u0026#39;SELECT (? + ?) sum\u0026#39;, [a, b], (err, row) =\u0026gt; { if (err) { console.error(err.message); } console.log(`The sum of ${a}and ${b}is ${row.sum}`); }); } Let’s run the parallelize.js program.\n\u0026gt;node parallelize.js The sum of 5 and 5 is 10 The sum of 1 and 1 is 2 The sum of 4 and 4 is 8 The sum of 3 and 3 is 6 The sum of 2 and 2 is 4 As you see in the output, the order of execution is not the same as it was called in the program.\nNotice that the statements execute in parallel, therefore, each time you run the program, the order of execution may be different.\nIn this tutorial, you have learned how to control the execution flow of the statements.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.controlling-flow-sqlite/","summary":"Summary: in this tutorial, you will learn how to control the execution flow of statements.\nThe sqlite3 module provides you with two methods for controlling the execution flow of statements. The serialize() method allows you to execute statements in serialized mode, while the parallelize() method executes the statements in parallel.\nLet’s look into each method in detail to understand how it works.\nExecuting statement in serialized mode with Database.serialize The serialize() method puts the execution mode into serialized mode.","title":"Node :: Controlling the Execution Flow of Statements"},{"content":"Summary: in this tutorial, you will learn how to query data from the SQLite database from a Node.js application using sqlite3 API.\nTo query data in SQLite database from a Node.js application, you use these steps:\n Open a database connection. Execute a SELECT statement and process the result set. Close the database connection.  The sqlite3 module provides you with some methods for querying data such as all(), each() and get().\nQuerying all rows with all() method The all() method allows you to execute an SQL query with specified parameters and call a callback to access the rows in the result set.\nThe following is the signature of the all() method:\ndb.all(sql,params,(err, rows ) =\u0026gt; { // process rows here }); The err argument stores the error detail in case there was an error occurred during the execution of the query. Otherwise, the err will be null. If the query is executed successfully, the rows argument contains the result set of the query.\nBecause the all() method retrieves all rows and places them in the memory, therefore, for the large result set, you should use the each() method.\nThe following example illustrates how to query data from the playlists table in the sample database using the all() method:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database let db = new sqlite3.Database(\u0026#39;./db/chinook.db\u0026#39;); let sql = `SELECT DISTINCT Name name FROM playlists ORDER BY name`; db.all(sql, [], (err, rows) =\u0026gt; { if (err) { throw err; } rows.forEach((row) =\u0026gt; { console.log(row.name); }); }); // close the database connection db.close(); Let’s run the program.\n\u0026gt;node all.js 90\u0026#39;s Music Audiobooks Brazilian Music Classical Classical 101 - Deep Cuts Classical 101 - Next Steps Classical 101 - The Basics Grunge Heavy Metal Classic Movies Music Music Videos On-The-Go 1 TV Shows The output shows all playlists as expected.\nQuery the first row in the result set When you know that the result set contains zero or one row e.g., querying a row based on the primary key or querying with only one aggregate function such as count, sum, max, min, etc., you can use the get() method of Database object.\ndb.get(sql, params, (err, row) =\u0026gt; { // process the row here }); The get() method executes an SQL query and calls the callback function on the first result row. In case the result set is empty, the row argument is undefined.\nThe following get.js program demonstrates how to query a playlist by its id:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database let db = new sqlite3.Database(\u0026#39;./db/chinook.db\u0026#39;); let sql = `SELECT PlaylistId id, Name name FROM playlists WHERE PlaylistId = ?`; let playlistId = 1; // first row only db.get(sql, [playlistId], (err, row) =\u0026gt; { if (err) { return console.error(err.message); } return row ? console.log(row.id, row.name) : console.log(`No playlist found with the id ${playlistId}`); }); // close the database connection db.close(); Let’s run the get.js program.\n\u0026gt;node get.js 1 \u0026#39;Music\u0026#39; The output shows the Music playlist which is correct.\nIf you change the playlistId to 0 and execute the get.js program again:\n\u0026gt;node get.js No playlist found with the id 0 It showed that no playlist found with id 0 as expected.\nQuery rows with each() method The each() method executes an SQL query with specified parameters and calls a callback for every row in the result set.\nThe following illustrates the signature of the each() method:\ndb.each(sql,params, (err, result) =\u0026gt; { // process each row here }); If the result set is empty, the callback is never called. In case there is an error, the err parameter contains the detailed information.\nThe following each.js program illustrates how to use the each() method to query customer’s data from the customers table.\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database let db = new sqlite3.Database(\u0026#39;../db/chinook.db\u0026#39;); let sql = `SELECT FirstName firstName, LastName lastName, Email email FROM customers WHERE Country = ? ORDER BY FirstName`; db.each(sql, [\u0026#39;USA\u0026#39;], (err, row) =\u0026gt; { if (err) { throw err; } console.log(`${row.firstName}${row.lastName}- ${row.email}`); }); // close the database connection db.close(); Let’s run the each.js program:\n\u0026gt;node each.js Dan Miller - dmiller@comcast.com Frank Harris - fharris@google.com Frank Ralston - fralston@gmail.com Heather Leacock - hleacock@gmail.com Jack Smith - jacksmith@microsoft.com John Gordon - johngordon22@yahoo.com Julia Barnett - jubarnett@gmail.com Kathy Chase - kachase@hotmail.com Michelle Brooks - michelleb@aol.com Patrick Gray - patrick.gray@aol.com Richard Cunningham - ricunningham@hotmail.com Tim Goyer - tgoyer@apple.com Victor Stevens - vstevens@yahoo.com As you see, the callback function was called for each row to print out the customer’s information.\nIn this tutorial, you have learned how to use various methods of the Database object to query data from the SQLite database.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.querying-sqlite/","summary":"Summary: in this tutorial, you will learn how to query data from the SQLite database from a Node.js application using sqlite3 API.\nTo query data in SQLite database from a Node.js application, you use these steps:\n Open a database connection. Execute a SELECT statement and process the result set. Close the database connection.  The sqlite3 module provides you with some methods for querying data such as all(), each() and get().","title":"Node :: Querying Data in SQLite Database from Node.js Applications"},{"content":"Summary: in this tutorial, you will learn how to connect to an SQLite database from Node.js applications.\nInstalling sqlite3 module To interact with the SQLite database, you need to download and install sqlite3 module. You can use npm to do so using the following command:\n\u0026gt; npm install sqlite3 After installing the sqlite3 module, you are ready to connect to a SQLite database from a Node.js application.\n@types도 같이 깔자.\n\u0026gt; npm install --save-dev @types/sqlite3 To connect to an SQLite database, you need to:\n First, import the sqlite3 module Second, call the Database() function of the sqlite3 module and pass the database information such as database file, opening mode, and a callback function.  Connecting to the in-memory database To open a database connection to an in-memory database, you use the following steps.\nFirst, import the sqlite3 module:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); Notice that the execution mode is set to verbose to produce long stack traces.\nSecond, create a Database object:\nlet db = new sqlite3.Database(\u0026#39;:memory:\u0026#39;); The sqlite3.Database() returns a Database object and opens the database connection automatically.\nThe sqlite3.Database() accepts a callback function that will be called when the database opened successfully or when an error occurred.\nThe callback function has the error object as the first parameter. If an error occurred, the error object is not null, otherwise, it is null.\nIf you don’t provide the callback function and an error occurred during opening the database, an error event will be emitted. In case the database is opened successfully, the open event is emitted regardless of whether a callback is provided or not.\nSo you now can open an SQLite database and provide the detailed information if an error occurred as follows:\nlet db = new sqlite3.Database(\u0026#39;:memory:\u0026#39;, (err) =\u0026gt; { if (err) { return console.error(err.message); } console.log(\u0026#39;Connected to the in-memory SQlite database.\u0026#39;); }); It is a good practice to close a database connection when you are done with it. To close a database connection, you call the close() method of the Database object as follows:\ndb.close(); The close() method will wait for all pending queries completed before actually closing the database.\nSimilar to the Database(), the close() method also accepts a callback that indicates whether an error occurred during closing the database connection.\ndb.close((err) =\u0026gt; { if (err) { return console.error(err.message); } console.log(\u0026#39;Close the database connection.\u0026#39;); }); The following illustrates the complete code for opening and closing an in-memory SQLite database:\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open database in memory let db = new sqlite3.Database(\u0026#39;:memory:\u0026#39;, (err) =\u0026gt; { if (err) { return console.error(err.message); } console.log(\u0026#39;Connected to the in-memory SQlite database.\u0026#39;); }); // close the database connection db.close((err) =\u0026gt; { if (err) { return console.error(err.message); } console.log(\u0026#39;Close the database connection.\u0026#39;); }); Let’s run the program to see how it works.\n\u0026gt; node connect.js Connected to the in-memory SQlite database. Close the database connection. As you can see, it works perfectly as expected.\nConnecting to a disk file database To connect to a disk file database, instead of passing the ':memory:' string, you pass the path to the database file.\nFor example, to connect to the chinook database file stored in the db folder, you use the following statement:\nchinook 데이터베이스 파일은 여기에서 받자.\nlet db = new sqlite3.Database(\u0026#39;./db/chinook.db\u0026#39;, (err) =\u0026gt; { if (err) { console.error(err.message); } console.log(\u0026#39;Connected to the chinook database.\u0026#39;); }); There are three opening modes:\n sqlite3.OPEN_READONLY: open the database for read-only. sqlite3.OPEN_READWRITE : open the database for reading and writting. sqlite3.OPEN_CREATE: open the database, if the database does not exist, create a new database.  The sqlite3.Database() accepts one or more mode as the second argument. By default, it uses the OPEN_READWRITE | OPEN_CREATE mode. It means that if the database does not exist, the new database will be created and is ready for read and write.\nTo open the chinook sample database for read and write, you can do it as follows:\nlet db = new sqlite3.Database(\u0026#39;./db/chinook.db\u0026#39;, sqlite3.OPEN_READWRITE, (err) =\u0026gt; { if (err) { console.error(err.message); } console.log(\u0026#39;Connected to the chinook database.\u0026#39;); }); The following example shows the complete code for opening the chinook database, querying data from the playlists table, and closing the database connection.\nconst sqlite3 = require(\u0026#39;sqlite3\u0026#39;).verbose(); // open the database let db = new sqlite3.Database(\u0026#39;./db/chinook.db\u0026#39;, sqlite3.OPEN_READWRITE, (err) =\u0026gt; { if (err) { console.error(err.message); } console.log(\u0026#39;Connected to the chinook database.\u0026#39;); }); db.serialize(() =\u0026gt; { db.each(`SELECT PlaylistId as id, Name as name FROM playlists`, (err, row) =\u0026gt; { if (err) { console.error(err.message); } console.log(row.id + \u0026#34;\\t\u0026#34; + row.name); }); }); db.close((err) =\u0026gt; { if (err) { console.error(err.message); } console.log(\u0026#39;Close the database connection.\u0026#39;); }); Note that you will learn how to query data in the next tutorial.\nIn this tutorial, you have learned how to connect to an SQLite database either in-memory or disk file based database.\nSee Also  https://www.sqlitetutorial.net/sqlite-nodejs/  ","permalink":"https://bynaki.github.io/posts/node.connecting-sqlite/","summary":"Summary: in this tutorial, you will learn how to connect to an SQLite database from Node.js applications.\nInstalling sqlite3 module To interact with the SQLite database, you need to download and install sqlite3 module. You can use npm to do so using the following command:\n\u0026gt; npm install sqlite3 After installing the sqlite3 module, you are ready to connect to a SQLite database from a Node.js application.\n@types도 같이 깔자.","title":"Node :: Connecting To SQLite Database Using Node.js"},{"content":"In this guide I will explain how to deploy a website to GitHub pages forcing HTTPS over a custom domain that is registered with AWS Route 53. We will set up our domain so that the www subdomain will redirect to the apex domain.\nSummary  Set up the GitHub repo Commit and push an index.html or use Jekyll Configure AWS Route 53  Step 1: Create GitHub repo and turn on GitHub Pages  If it does not exist yet, create a repository using the naming pattern your-github-username.github.io. Since my username is benwiz my repository is called benwiz.github.io . Click the Settings tab and scroll down the GitHub Pages section From the Source dropdown select master branch Click Save  Step 2: Push source code to GitHub  Clone the repo to your local machine  git clone git@github.com:your-github-username/your-github-username.github.io.git \u0026amp;\u0026amp; cd your-github-username.github.io  Create an index.html file with some content  echo \u0026quot;Hello GitHub Pages!\u0026quot; \u0026gt; index.html  Looking forward, we will need to have a file named CNAME that contains a single row: your custom domain. My CNAME file has the following contents.  benwiz.com  Push the files to GitHub  git add . \u0026amp;\u0026amp; git commit -m 'Create content and CNAME record' \u0026amp;\u0026amp; git push Step 3: Confirm that GitHub pages has been deployed Visit http://your-github-username.github.io and https://your-github-username.github.io. You should see the contents of your index.html file at both the unsecured and secured addresses.\nStep 4: Configure AWS Route 53 to use your custom vanity domain  Log into the AWS console and go to the Route 53 dashboard. Click Hosted zones Click the domain you would like to use Click Create Record Set Do not enter anything into the Name field Under the Type dropdown, select A — IPv4 addresses The Alias toggle should be set to No Enter the following four IP addresses into the value text area. Then click Save Record Set.  185.199.108.153 185.199.109.153 185.199.110.153 185.199.111.153  Click Create Record Set, again Into the Name field, enter www Under the Type dropdown, select A — IPv4 addresses, again The Alias toggle should be set to Yes, unlike before In the Alias Target field, select the apex domain we previously set up. For me this is *benwiz.*com. Click Save Record Set, again  Step 5: Configure GitHub to serve over your custom domain  Return to your GitHub repository’s settings tab Scroll down to the GitHub Pages section In the Custom domain field enter your custom domain: your-custom-domain.com Click Save Check Enforce HTTPS  Step 6: Confirm that your page is accessible at your custom domain Visit https://your-custom-domain.com. You should see the contents of your index.html.\n Visit https://www.your-custom-domain.com. You should be redirected to https://your-custom-domain.com. Visit http://your-custom-domain.com. You should be redirected to https://your-custom-domain.com. Visit http://www.your-custom-domain.com. You should be redirected to https://your-custom-domain.com.  ","permalink":"https://bynaki.github.io/posts/aws.route53-github/","summary":"In this guide I will explain how to deploy a website to GitHub pages forcing HTTPS over a custom domain that is registered with AWS Route 53. We will set up our domain so that the www subdomain will redirect to the apex domain.\nSummary  Set up the GitHub repo Commit and push an index.html or use Jekyll Configure AWS Route 53  Step 1: Create GitHub repo and turn on GitHub Pages  If it does not exist yet, create a repository using the naming pattern your-github-username.","title":"AWS :: How to deploy GitHub pages with AWS Route 53 registered custom domain and force HTTPS"},{"content":"You can capture the entire screen, a window, or just a portion of the screen.\nHow to take a screenshot on your Mac  To take a screenshot, press and hold these three keys together: Shift, Command, and 3. If you see a thumbnail in the corner of your screen, click it to edit the screenshot. Or wait for the screenshot to save to your desktop.  How to capture a portion of the screen  Press and hold these three keys together: Shift, Command, and 4. Drag the crosshair to select the area of the screen to capture. To move the selection, press and hold Space bar while dragging. To cancel taking the screenshot, press the Esc (Escape) key.  To take the screenshot, release your mouse or trackpad button. If you see a thumbnail in the corner of your screen, click it to edit the screenshot. Or wait for the screenshot to save to your desktop.  How to capture a window or menu  Open the window or menu that you want to capture. Press and hold these keys together: Shift, Command, 4, and Space bar. The pointer changes to a camera icon . To cancel taking the screenshot, press the Esc (Escape) key.  Click the window or menu to capture it. To exclude the window\u0026rsquo;s shadow from the screenshot, press and hold the Option key while you click. If you see a thumbnail in the corner of your screen, click it to edit the screenshot. Or wait for the screenshot to save to your desktop.  Where to find screenshots By default, screenshots save to your desktop with the name ”Screen Shot [date] at [time].png.”\nIn macOS Mojave or later, you can change the default location of saved screenshots from the Options menu in the Screenshot app. You can also drag the thumbnail to a folder or document.\nLearn more  In macOS Mojave or later, you can also set a timer and choose where screenshots are saved with the Screenshot app. To open the app, press and hold these three keys together: Shift, Command, and 5. Learn more about the Screenshot app. Some apps, such as the Apple TV app, might not let you take screenshots of their windows. To copy a screenshot to the Clipboard, press and hold the Control key while you take the screenshot. You can then paste the screenshot somewhere else. Or use Universal Clipboard to paste it on another Apple device.  ","permalink":"https://bynaki.github.io/posts/mac.screenshot/","summary":"You can capture the entire screen, a window, or just a portion of the screen.\nHow to take a screenshot on your Mac  To take a screenshot, press and hold these three keys together: Shift, Command, and 3. If you see a thumbnail in the corner of your screen, click it to edit the screenshot. Or wait for the screenshot to save to your desktop.  How to capture a portion of the screen  Press and hold these three keys together: Shift, Command, and 4.","title":"Mac :: Take a screenshot on your Mac"},{"content":"Is there a quicker way of just updating all the dependencies, including major version changes? So, like npm update but for major version updates as well?\nYes, there is a tool called npm-check-updates that will do this. Just run the following command:\nnpx npm-check-updates -u This will update the dependencies to the latest versions (including major version changes) in the package.json file. If we are happy to go ahead with the upgrades we need to run the following command:\nnpm install This will then upgrade the packages in the node_modules folder, and the package-lock.json file will be updated as well.\n","permalink":"https://bynaki.github.io/posts/node.upgrading-npm/","summary":"Is there a quicker way of just updating all the dependencies, including major version changes? So, like npm update but for major version updates as well?\nYes, there is a tool called npm-check-updates that will do this. Just run the following command:\nnpx npm-check-updates -u This will update the dependencies to the latest versions (including major version changes) in the package.json file. If we are happy to go ahead with the upgrades we need to run the following command:","title":"Node :: Upgrading npm"},{"content":"오래된 프로젝트의 기본 branch 이름이 master라면 main으로 변경하자.\ngithub 에서 Settings \u0026gt; Branches \u0026gt; Default branch 에서 master 를 main 으로 변경한 후 로컬에서 다음을 실행한다.\ngit branch -m master main git fetch origin git branch -u origin/main main git remote set-head origin -a git int 할때 기본 branch를 main으로 하기 위한 config 설정.\n$ git config --global init.defaultBranch main ","permalink":"https://bynaki.github.io/posts/git.default-branch-main/","summary":"오래된 프로젝트의 기본 branch 이름이 master라면 main으로 변경하자.\ngithub 에서 Settings \u0026gt; Branches \u0026gt; Default branch 에서 master 를 main 으로 변경한 후 로컬에서 다음을 실행한다.\ngit branch -m master main git fetch origin git branch -u origin/main main git remote set-head origin -a git int 할때 기본 branch를 main으로 하기 위한 config 설정.\n$ git config --global init.defaultBranch main ","title":"Git :: Default Branch를 'master'에서 'main'으로 변경"},{"content":"웹 폰트 또한 font-family 속성을 사용하지만, @font-face 지시어(directive)라는 CSS 명령어를 사용해서 웹 브라우저에게 해당 서체를 다운로드할 것을 알리면서 사용할 수 있습니다.\n웹 폰트를 위해 사용하는 CSS 코드는 매우 간단하며, 두 개의 CSS 명령어만이 필요합니다.\n @font-face 지시어는 웹 브라우저에게 서체 이름과 다운받을 위치를 알려줍니다. 이 명령어의 동작 방식은 뒤에서 살펴봅니다. font-family 속성의 사용법은 위에서 언급한 일반 폰트의 사용법과 같습니다. 일단 @font-face 를 사용해 브라우저에게 서체를 다운받으라 알린 다음에는, 어느 CSS에서도 일반 폰트와 동일하게 font-family를 통해 사용할 수 있게 됩니다.  Web Font Sysntax 웹 폰트의 마법은 @font-face 지시어라는 CSS 명령어부터 시작됩니다. 이 명령어는 사용할 폰트의 이름 및 해당 폰트를 다운받을 수 있는 위치를 브라우저에게 알리는 명령어입니다. 아래 코드에서 간단히 사용 방법을 살펴봅니다.\n@font-face { font-family: \u0026lt;a-remote-font-name\u0026gt; src: \u0026lt;source\u0026gt; [, \u0026lt;source\u0026gt;]*; [font-weight: \u0026lt;weight\u0026gt;]; [font-style: \u0026lt;style\u0026gt;]; } 속성값들의 내용은 아래와 같습니다.\n \u0026lt;a-remote-font-name\u0026gt; : font 속성에서 폰트명(font face)으로 지정될 이름을 설정한다. \u0026lt;source\u0026gt; : 원격 폰트(remote font) 파일의 위치를 나타내는 URL 값을 지정하거나, 사용자 컴퓨터에 설치된 폰트명을 local(\u0026ldquo;Font Name\u0026rdquo;)형식으로 지정하는 속성이다. \u0026lt;weight\u0026gt; : 폰트의 굵기(font weight) 값. \u0026lt;style\u0026gt; : 폰트 스타일(font style) 값.  Usage @font-face { font-family: \u0026#39;MaruBuri-Regular\u0026#39;; src: url(\u0026#39;https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_20-10-21@1.0/MaruBuri-Regular.woff\u0026#39;) format(\u0026#39;woff\u0026#39;); font-weight: normal; font-style: normal; } body { font-family:\u0026#39;나눔고딕\u0026#39;, \u0026#39;NanumGothic\u0026#39;, \u0026#39;MaruBuri-Regular\u0026#39;; } See Also  https://webclub.tistory.com/261 Google Fonts Adobe Fonts cufon 눈누 Font Squirrel (웹폰트 생성기) 이롭게 바탕체  ","permalink":"https://bynaki.github.io/posts/css.font-face/","summary":"웹 폰트 또한 font-family 속성을 사용하지만, @font-face 지시어(directive)라는 CSS 명령어를 사용해서 웹 브라우저에게 해당 서체를 다운로드할 것을 알리면서 사용할 수 있습니다.\n웹 폰트를 위해 사용하는 CSS 코드는 매우 간단하며, 두 개의 CSS 명령어만이 필요합니다.\n @font-face 지시어는 웹 브라우저에게 서체 이름과 다운받을 위치를 알려줍니다. 이 명령어의 동작 방식은 뒤에서 살펴봅니다. font-family 속성의 사용법은 위에서 언급한 일반 폰트의 사용법과 같습니다. 일단 @font-face 를 사용해 브라우저에게 서체를 다운받으라 알린 다음에는, 어느 CSS에서도 일반 폰트와 동일하게 font-family를 통해 사용할 수 있게 됩니다.","title":"CSS :: Web Font (@font-face)"},{"content":" hammerspoon은 macOS에서만 돌아가는 자동화 툴이다. Lua를 내장하고 있다. 마음에 든다.  What is Hammerspoon? This is a tool for powerful automation of OS X. At its core, Hammerspoon is just a bridge between the operating system and a Lua scripting engine.\nWhat gives Hammerspoon its power is a set of extensions that expose specific pieces of system functionality, to the user. With these, you can write Lua scripts to control many aspects of your OS X environment.\nHow do I install it? Manually  Download the latest release Drag Hammerspoon.app from your Downloads folder to Applications  Homebrew  brew install hammerspoon --cask  사용법  ~/.hammerspoon/init.lua 코딩한다. 아래 메뉴에 Open Config를 선택해도 된다. 아래 메뉴에 Reload Config를 선택해 Reload 한다. Console 창을 보고 싶으면 아래 메뉴에 Console...을 선택한다.  What next? Out of the box, Hammerspoon does nothing - you will need to create ~/.hammerspoon/init.lua and fill it with useful code. There are several resources which can help you:\n Getting Started Guide API docs FAQ Sample Configurations supplied by various users Contribution Guide for developers looking to get involved An IRC channel for general chat/support/development (#hammerspoon on Libera) Google Group for support  나의 Hammerspoon init.lua:\ndo -- Reload Hammerspoon hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;r\u0026#39;, hs.reload) end do -- Launch or Focus Terminal hs.hotkey.bind({\u0026#39;cmd\u0026#39;}, \u0026#39;return\u0026#39;, function() hs.application.launchOrFocus(\u0026#39;Alacritty\u0026#39;) end) end do -- Window Hints hs.hints.hintChars = {\u0026#39;A\u0026#39;, \u0026#39;S\u0026#39;, \u0026#39;D\u0026#39;, \u0026#39;F\u0026#39;, \u0026#39;Q\u0026#39;, \u0026#39;W\u0026#39;, \u0026#39;E\u0026#39;, \u0026#39;R\u0026#39;} hs.hotkey.bind({\u0026#39;shift\u0026#39;}, \u0026#39;tab\u0026#39;, hs.hints.windowHints) end do -- 윈도우창 크기 조절 local function moveToLeft() local win = hs.window.focusedWindow() local frame = win:frame() local screen = win:screen():frame() if frame.x == screen.x and frame.w == math.floor(screen.w / 2) then frame.w = screen.w / 3 elseif frame.x == screen.x and frame.w == math.floor(screen.w / 3) then frame.w = screen.w / 1.5 else frame.w = screen.w / 2 end frame.x = screen.x frame.y = screen.y frame.h = screen.h win:setFrame(frame) end local function moveToRight() local win = hs.window.focusedWindow() local frame = win:frame() local screen = win:screen():frame() if frame.x ~= screen.x and frame.w == math.floor(screen.w / 2) then frame.w = screen.w / 3 elseif frame.x ~= screen.x and frame.w == math.floor(screen.w / 3) then frame.w = screen.w / 1.5 else frame.w = screen.w / 2 end frame.x = screen.x + (screen.w - frame.w) frame.y = screen.y frame.h = screen.h win:setFrame(frame) end local function moveToTop() local win = hs.window.focusedWindow() local frame = win:frame() local screen = win:screen():frame() if frame.y == screen.y and frame.h == math.floor(screen.h / 2) then frame.h = screen.h / 3 elseif frame.y == screen.y and frame.h == math.floor(screen.h / 3) then frame.h = screen.h / 1.5 else frame.h = screen.h / 2 end frame.y = screen.y win:setFrame(frame) end local function moveToBottom() local win = hs.window.focusedWindow() local frame = win:frame() local screen = win:screen():frame() if frame.y ~= screen.y and frame.h == math.floor(screen.h / 2) then frame.h = screen.h / 3 elseif frame.y ~= screen.y and frame.h == math.floor(screen.h / 3) then frame.h = screen.h / 1.5 else frame.h = screen.h / 2 end frame.y = screen.y + (screen.h - frame.h) win:setFrame(frame) end local function maxWindow() local win = hs.window.focusedWindow() local frame = win:frame() local screen = win:screen():frame() frame.x = screen.x frame.y = screen.y frame.w = screen.w frame.h = screen.h win:setFrame(frame) end -- 키 맵핑 hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;left\u0026#39;, moveToLeft) hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;Right\u0026#39;, moveToRight) hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;Up\u0026#39;, moveToTop) hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;Down\u0026#39;, moveToBottom) hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;Down\u0026#39;, moveToBottom) hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;Return\u0026#39;, maxWindow) end -- do -- -- hs.hotkey.bind({\u0026#39;ctrl\u0026#39;, \u0026#39;option\u0026#39;, \u0026#39;cmd\u0026#39;}, \u0026#39;i\u0026#39;, function() -- local input_source = hs.keycodes.currentSourceID() -- print(input_source) -- end) -- end do -- Change Input Source :: 한영키 지정 local inputSource = { english = \u0026#34;com.apple.keylayout.ABC\u0026#34;, korean = \u0026#34;com.apple.inputmethod.Korean.2SetKorean\u0026#34;, } local function changeInput() local current = hs.keycodes.currentSourceID() local nextInput = nil if current == inputSource.english then nextInput = inputSource.korean else nextInput = inputSource.english end hs.keycodes.currentSourceID(nextInput) end hs.hotkey.bind({\u0026#39;shift\u0026#39;}, \u0026#39;space\u0026#39;, changeInput) hs.hotkey.bind({}, \u0026#39;f13\u0026#39;, changeInput) end do -- Esc키 눌렀을때 강제로 영문키로 변경 for Vim local inputEng = \u0026#39;com.apple.keylayout.ABC\u0026#39; local function escapeWithChangedInput() local input_source = hs.keycodes.currentSourceID() if not (input_source == inputEng) then hs.keycodes.currentSourceID(inputEng) end hs.eventtap.keyStroke({}, \u0026#39;escape\u0026#39;) end -- hs.hotkey.bind({\u0026#39;ctrl\u0026#39;}, \u0026#39;c\u0026#39;, escapeWithChangedInput) hs.hotkey.bind({}, \u0026#39;f14\u0026#39;, escapeWithChangedInput) end do -- Remapping Keys local FRemap = require(\u0026#39;foundation_remapping\u0026#39;) local remapper = FRemap.new() remapper:remap(\u0026#39;rcmd\u0026#39;, \u0026#39;f13\u0026#39;) remapper:remap(\u0026#39;capslock\u0026#39;, \u0026#39;f14\u0026#39;) remapper:register() end 마지막 Remmapping Keys 섹션을 보면 foundation_remapping plug-in을 불러 왔다. foundation_remapping 다운로드 받아 ~/.hammerspoon에 저장해 두자.\nSeeAlos  Hammerspoon Spoons Github page Sample Configurations johngrib 한글문서  ","permalink":"https://bynaki.github.io/posts/hammerspoon/","summary":"hammerspoon은 macOS에서만 돌아가는 자동화 툴이다. Lua를 내장하고 있다. 마음에 든다.  What is Hammerspoon? This is a tool for powerful automation of OS X. At its core, Hammerspoon is just a bridge between the operating system and a Lua scripting engine.\nWhat gives Hammerspoon its power is a set of extensions that expose specific pieces of system functionality, to the user. With these, you can write Lua scripts to control many aspects of your OS X environment.","title":"Hammerspoon"},{"content":"Create a Hugo site using the beautiful Ananke theme.\n This quick start uses macOS in the examples. For instructions about how to install Hugo on other operating systems, see install.\nIt is recommended to have Git installed to run this tutorial.\nFor other approaches learning Hugo like book or a video tutorial refer to the external learning resources page.\n Step 1: Install Hugo  Homebrew and MacPorts, package managers for macOS, can be installed from brew.sh or macports.org respectively. See install if you are running Windows etc.\n brew install hugo # or port install hugo To verify your new install:\nhugo version Step 2: Create a New Site hugo new site quickstart The above will create a new Hugo site in a folder named quickstart.\nStep 3: Add a Theme See themes.gohugo.io for a list of themes to consider. This quickstart uses the beautiful Ananke theme.\nFirst, download the theme from GitHub and add it to your site’s themes directory:\ncd quickstart git init git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke Then, add the theme to the site configuration:\necho theme = \\\u0026#34;ananke\\\u0026#34; \u0026gt;\u0026gt; config.toml Step 4: Add Some Content You can manually create content files (for example as content/\u0026lt;CATEGORY\u0026gt;/\u0026lt;FILE\u0026gt;.\u0026lt;FORMAT\u0026gt;) and provide metadata in them, however you can use the new command to do a few things for you (like add title and date):\nhugo new posts/my-first-post.md Edit the newly created content file if you want, it will start with something like this:\n--- title: \u0026quot;My First Post\u0026quot; date: 2019-03-26T08:47:11+01:00 draft: true ---  Drafts do not get deployed; once you finish a post, update the header of the post to say draft: false. More info here.\n 위 설정은 /archetypes/default.md와 연계된다. 만약, 자기만의 것을 설정하고 싶다면 default.md를 고치거나 아니면 새로운 파일로 하고 싶다면 (예: post.md라고 한다면) 파일을 생성하고 아래와 같이 하자.\nhugo new --kind post posts/my-first-post.md Step 5: Start the Hugo server Now, start the Hugo server with drafts enabled:\n▶ hugo server -D | EN +------------------+----+ Pages | 10 Paginator pages | 0 Non-page files | 0 Static files | 3 Processed images | 0 Aliases | 1 Sitemaps | 1 Cleaned | 0 Total in 11 ms Watching for changes in /Users/bep/quickstart/{content,data,layouts,static,themes} Watching for config changes in /Users/bep/quickstart/config.toml Environment: \u0026#34;development\u0026#34; Serving pages from memory Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender Web Server is available at http://localhost:1313/ (bind address 127.0.0.1) Press Ctrl+C to stop Navigate to your new site at http://localhost:1313/.\nFeel free to edit or add new content and simply refresh in browser to see changes quickly (You might need to force refresh in webbrowser, something like Ctrl-R usually works).\nStep 6: Customize the Theme Your new site already looks great, but you will want to tweak it a little before you release it to the public.\nSite Configuration Open up config.toml in a text editor:\nbaseURL = \u0026#34;https://example.org/\u0026#34; languageCode = \u0026#34;en-us\u0026#34; title = \u0026#34;My New Hugo Site\u0026#34; theme = \u0026#34;ananke\u0026#34; Replace the title above with something more personal. Also, if you already have a domain ready, set the baseURL. Note that this value is not needed when running the local development server.\n Tip: Make the changes to the site configuration or any other file in your site while the Hugo server is running, and you will see the changes in the browser right away, though you may need to clear your cache.\n For theme specific configuration options, see the theme site.\nFor further theme customization, see Customize a Theme.\nStep 7: Build static pages It is simple. Just call:\nhugo -D Output will be in ./public/ directory by default (-d/--destination flag to change it, or set publishdir in the config file).\nSee Also  https://gohugo.io/getting-started/quick-start/ https://ialy1595.github.io/post/blog-construct-1/ https://golangkorea.github.io/series/hugo-introduction/ PaperMod Theme  ","permalink":"https://bynaki.github.io/posts/hugo.quick-start/","summary":"Create a Hugo site using the beautiful Ananke theme.\n This quick start uses macOS in the examples. For instructions about how to install Hugo on other operating systems, see install.\nIt is recommended to have Git installed to run this tutorial.\nFor other approaches learning Hugo like book or a video tutorial refer to the external learning resources page.\n Step 1: Install Hugo  Homebrew and MacPorts, package managers for macOS, can be installed from brew.","title":"Hugo :: Quick Start"},{"content":"This article offers a sample of basic Markdown syntax that can be used in Hugo content files, also it shows whether basic HTML elements are decorated with CSS in a Hugo theme.\nHeadings The following HTML \u0026lt;h1\u0026gt;—\u0026lt;h6\u0026gt; elements represent six levels of section headings. \u0026lt;h1\u0026gt; is the highest section level while \u0026lt;h6\u0026gt; is the lowest.\nH1 H2 H3 H4 H5 H6 Paragraph Xerum, quo qui aut unt expliquam qui dolut labo. Aque venitatiusda cum, voluptionse latur sitiae dolessi aut parist aut dollo enim qui voluptate ma dolestendit peritin re plis aut quas inctum laceat est volestemque commosa as cus endigna tectur, offic to cor sequas etum rerum idem sintibus eiur? Quianimin porecus evelectur, cum que nis nust voloribus ratem aut omnimi, sitatur? Quiatem. Nam, omnis sum am facea corem alique molestrunt et eos evelece arcillit ut aut eos eos nus, sin conecerem erum fuga. Ri oditatquam, ad quibus unda veliamenimin cusam et facea ipsamus es exerum sitate dolores editium rerore eost, temped molorro ratiae volorro te reribus dolorer sperchicium faceata tiustia prat.\nItatur? Quiatae cullecum rem ent aut odis in re eossequodi nonsequ idebis ne sapicia is sinveli squiatum, core et que aut hariosam ex eat.\nBlockquotes The blockquote element represents content that is quoted from another source, optionally with a citation which must be within a footer or cite element, and optionally with in-line changes such as annotations and abbreviations.\nBlockquote without attribution  Tiam, ad mint andaepu dandae nostion secatur sequo quae. Note that you can use Markdown syntax within a blockquote.\n Blockquote with attribution  Don\u0026rsquo;t communicate by sharing memory, share memory by communicating.\n— Rob Pike1 Tables Tables aren\u0026rsquo;t part of the core Markdown spec, but Hugo supports supports them out-of-the-box.\n   Name Age     Bob 27   Alice 23    Inline Markdown within tables    Italics Bold Code     italics bold code    Code Blocks Code block with backticks \u0026lt;!DOCTYPE html\u0026gt; \u0026lt;html lang=\u0026#34;en\u0026#34;\u0026gt; \u0026lt;head\u0026gt; \u0026lt;meta charset=\u0026#34;utf-8\u0026#34; /\u0026gt; \u0026lt;title\u0026gt;Example HTML5 Document\u0026lt;/title\u0026gt; \u0026lt;/head\u0026gt; \u0026lt;body\u0026gt; \u0026lt;p\u0026gt;Test\u0026lt;/p\u0026gt; \u0026lt;/body\u0026gt; \u0026lt;/html\u0026gt; Code block indented with four spaces \u0026lt;!doctype html\u0026gt; \u0026lt;html lang=\u0026quot;en\u0026quot;\u0026gt; \u0026lt;head\u0026gt; \u0026lt;meta charset=\u0026quot;utf-8\u0026quot;\u0026gt; \u0026lt;title\u0026gt;Example HTML5 Document\u0026lt;/title\u0026gt; \u0026lt;/head\u0026gt; \u0026lt;body\u0026gt; \u0026lt;p\u0026gt;Test\u0026lt;/p\u0026gt; \u0026lt;/body\u0026gt; \u0026lt;/html\u0026gt;  Code block with Hugo\u0026rsquo;s internal highlight shortcode \u0026lt;!doctype html\u0026gt; \u0026lt;html lang=\u0026#34;en\u0026#34;\u0026gt; \u0026lt;head\u0026gt; \u0026lt;meta charset=\u0026#34;utf-8\u0026#34;\u0026gt; \u0026lt;title\u0026gt;Example HTML5 Document\u0026lt;/title\u0026gt; \u0026lt;/head\u0026gt; \u0026lt;body\u0026gt; \u0026lt;p\u0026gt;Test\u0026lt;/p\u0026gt; \u0026lt;/body\u0026gt; \u0026lt;/html\u0026gt; Gist  List Types Ordered List  First item Second item Third item  Unordered List  List item Another item And another item  Nested list  Fruit  Apple Orange Banana   Dairy  Milk Cheese    Other Elements — abbr, sub, sup, kbd, mark GIFis a bitmap image format.\nH2O\nXn+ Yn= ZnPress CTRL+ALT+Deleteto end the session.\nMost salamandersare nocturnal, and hunt for insects, worms, and other small creatures.\nLink Github\nImage   The above quote is excerpted from Rob Pike\u0026rsquo;s talk during Gopherfest, November 18, 2015.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n  ","permalink":"https://bynaki.github.io/posts/markdown.syntax/","summary":"\u003cp\u003eThis article offers a sample of basic Markdown syntax that can be used in Hugo content files, also it shows whether basic HTML elements are decorated with CSS in a Hugo theme.\u003c/p\u003e","title":"Markdown :: Syntax"},{"content":"About submodule.\nAdd Submodule 서브모듈 추가 하기\n$ git submodule add https://github.com/chaconinc/DbConnector 기본적으로 서브모듈은 프로젝트 저장소의 이름으로 디렉토리를 만든다. 예제에서는 DbConnector라는 이름으로 만든다. 명령의 마지막에 원하는 이름을 넣어 다른 디렉토리 이름으로 서브모듈을 추가할 수도 있다. 우선 .gitmodules 파일이 만들어졌다. 이 파일은 서브디렉토리와 하위 프로젝트 URL의 매핑 정보를 담은 설정파일이다.\n[submodule \u0026quot;DbConnector\u0026quot;] path = DbConnector url = https://github.com/chaconinc/DbConnector Submodule 포함한 프로젝트 Clone 서브모듈을 포함하는 프로젝트를 Clone 하는 예제를 살펴본다. 이런 프로젝트를 Clone 하면 기본적으로 서브모듈 디렉토리는 빈 디렉토리이다.\n$ git clone https://github.com/chaconinc/MainProject 분명히 DbConnector 디렉토리는 있지만 비어 있다. 서브모듈에 관련된 두 명령을 실행해야 완전히 Clone 과정이 끝난다. 먼저 git submodule init 명령을 실행하면 서브모듈 정보를 기반으로 로컬 환경설정 파일이 준비된다. 이후 git submodule update 명령으로 서브모듈의 리모트 저장소에서 데이터를 가져오고 서브모듈을 포함한 프로젝트의 현재 스냅샷에서 Checkout 해야 할 커밋 정보를 가져와서 서브모듈 프로젝트에 대한 Checkout을 한다.\n$ git submodule init $ git submodule update DbConnector 디렉토리는 마지막으로 커밋을 했던 상태로 복원된다.\n하지만, 같은 과정을 더 간단하게 실행하는 방법도 있다. 메인 프로젝트를 Clone 할 때 git clone 명령 뒤에 --recurse-submodules 옵션을 붙이면 서브모듈을 자동으로 초기화하고 업데이트한다.\n$ git clone --recurse-submodules https://github.com/chaconinc/MainProject Submodule 포함한 프로젝트 작업 서브모듈 디렉토리에서 Fetch 명령과 Merge 명령을 실행하지 않아도 git submodule update --remote 명령을 실행하면 Git이 알아서 서브모듈 프로젝트를 Fetch 하고 업데이트한다.\n$ git submodule update --remote DbConnector Submodule Push 서브모듈의 변경사항을 Push 하지 않은 채로 메인 프로젝트에서 커밋을 Push 하면 안 된다. 변경 사항을 Checkout 한 다른 사람은 서브모듈이 의존하는 코드를 어디서도 가져올 수 없는 상황이 돼 곤란해진다. 서브모듈의 변경사항은 우리의 로컬에만 있다.\n이런 불상사가 발생하지 않도록 하려면 메인 프로젝트를 Push 하기 전에 서브모듈을 모두 Push 했는지 검사하도록 Git에게 물어보면 된다. git push 명령에 --recurse-submodules 옵션을 주고 이 옵션의 값으로 check 나 on-demand 를 설정한다. check 는 간단히 서브모듈의 로컬 커밋이 Push 되지 않은 상태라면 현재의 `Push 명령도 실패하도록 하는 옵션이다.\n$ git push --recurse-submodules=check The following submodule paths contain changes that can not be found on any remote: DbConnector Please try git push --recurse-submodules=on-demand or cd to the path and use git push to push them to a remote. 예제에서 볼 수 있는 대로 이러한 상황에서 다음으로 무엇을 해야 하는지 Git은 도움을 준다. 가장 단순한 방법은 각 서브모듈 디렉토리로 가서 직접 일일이 Push를 해서 외부로 공유하고 나서 메인 프로젝트를 Push 하는 것이다. 이 옵션이 항상 적용되도록 하고 싶으면 git config push.recurseSubmodules check 명령으로 설정한다.\n옵션으로 설정할 수 있는 다른 값으로 on-demand 값이 있는데, 이 값으로 설정하면 Git이 Push를 대신 시도한다.\n$ git push --recurse-submodules=on-demand Pushing submodule \u0026#39;DbConnector\u0026#39; Counting objects: 9, done. Delta compression using up to 8 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (9/9), 917 bytes | 0 bytes/s, done. Total 9 (delta 3), reused 0 (delta 0) To https://github.com/chaconinc/DbConnector c75e92a..82d2ad3 stable -\u0026gt; stable Counting objects: 2, done. Delta compression using up to 8 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (2/2), 266 bytes | 0 bytes/s, done. Total 2 (delta 1), reused 0 (delta 0) To https://github.com/chaconinc/MainProject 3d6d338..9a377d1 master -\u0026gt; master 위에서 보듯이 Git이 메인 프로젝트를 Push 하기 전에 DbConnector 모듈로 들어가서 Push를 한다. 모종의 이유로 서브모듈 Push에 실패한다면 메인 프로젝트의 Push 또한 실패하게 된다. git config push.recurseSubmodules on-demand 명령으로 설정할 수 있다.\nSee Also  7.11 Git 도구 - 서브모듈  ","permalink":"https://bynaki.github.io/posts/git.submodule/","summary":"About submodule.\nAdd Submodule 서브모듈 추가 하기\n$ git submodule add https://github.com/chaconinc/DbConnector 기본적으로 서브모듈은 프로젝트 저장소의 이름으로 디렉토리를 만든다. 예제에서는 DbConnector라는 이름으로 만든다. 명령의 마지막에 원하는 이름을 넣어 다른 디렉토리 이름으로 서브모듈을 추가할 수도 있다. 우선 .gitmodules 파일이 만들어졌다. 이 파일은 서브디렉토리와 하위 프로젝트 URL의 매핑 정보를 담은 설정파일이다.\n[submodule \u0026quot;DbConnector\u0026quot;] path = DbConnector url = https://github.com/chaconinc/DbConnector Submodule 포함한 프로젝트 Clone 서브모듈을 포함하는 프로젝트를 Clone 하는 예제를 살펴본다. 이런 프로젝트를 Clone 하면 기본적으로 서브모듈 디렉토리는 빈 디렉토리이다.","title":"Git :: Submodule"},{"content":"Debugging tests with Visual Studio Code\nYou can debug your tests using Visual Studio Code.\nDebugging with the debug terminal You can use VS Code\u0026rsquo;s “JavaScript Debug Terminal” to automatically debug AVA run on the command-line.\n From the Command Palette (F1or command + shift + p/ control + shift + p), run Debug: Create JavaScript Debug Terminal Run npx ava in the terminal  Creating a launch configuration Alternatively you can create a launch configuration, which makes it easier to debug individual test files.\n Open a workspace for your project. In the sidebar click the Debug handle. Create a launch.json file. Select the Node.js environment. Add following to the configurations array and save changes:  { \u0026#34;type\u0026#34;: \u0026#34;node\u0026#34;, \u0026#34;request\u0026#34;: \u0026#34;launch\u0026#34;, \u0026#34;name\u0026#34;: \u0026#34;Debug AVA test file\u0026#34;, \u0026#34;runtimeExecutable\u0026#34;: \u0026#34;${workspaceFolder}/node_modules/.bin/ava\u0026#34;, \u0026#34;runtimeArgs\u0026#34;: [ \u0026#34;${file}\u0026#34; ], \u0026#34;outputCapture\u0026#34;: \u0026#34;std\u0026#34;, \u0026#34;skipFiles\u0026#34;: [ \u0026#34;\u0026lt;node_internals\u0026gt;/**/*.js\u0026#34; ] } Using the debugger Open the file(s) you want to debug. You can set breakpoints or use the debugger keyword.\nNow, with a test file open, from the Debug menu run the Debug AVA test file configuration.\nDebugging precompiled tests If you compile your test files into a different directory, and run the tests from that directory, the above configuration won\u0026rsquo;t work.\nAssuming the names of your test files are unique you could try the following configuration instead. This assumes the compile output is written to the build directory. Adjust as appropriate:\n{ \u0026#34;type\u0026#34;: \u0026#34;node\u0026#34;, \u0026#34;request\u0026#34;: \u0026#34;launch\u0026#34;, \u0026#34;name\u0026#34;: \u0026#34;Debug AVA test file\u0026#34;, \u0026#34;runtimeExecutable\u0026#34;: \u0026#34;${workspaceFolder}/node_modules/.bin/ava\u0026#34;, \u0026#34;runtimeArgs\u0026#34;: [ \u0026#34;build/**/${fileBasenameNoExtension}.*\u0026#34; ], \u0026#34;outputCapture\u0026#34;: \u0026#34;std\u0026#34;, \u0026#34;skipFiles\u0026#34;: [ \u0026#34;\u0026lt;node_internals\u0026gt;/**/*.js\u0026#34; ] } Serial debugging By default AVA runs tests concurrently. This may complicate debugging. Instead make sure AVA runs only one test at a time.\nNote that, if your tests aren\u0026rsquo;t properly isolated, certain test failures may not appear when running the tests serially.\nIf you use the debug terminal make sure to invoke AVA with npx ava --serial.\nOr, if you\u0026rsquo;re using a launch configuration, add the --serial argument:\n{ \u0026#34;type\u0026#34;: \u0026#34;node\u0026#34;, \u0026#34;request\u0026#34;: \u0026#34;launch\u0026#34;, \u0026#34;name\u0026#34;: \u0026#34;Debug AVA test file\u0026#34;, \u0026#34;runtimeExecutable\u0026#34;: \u0026#34;${workspaceFolder}/node_modules/.bin/ava\u0026#34;, \u0026#34;runtimeArgs\u0026#34;: [ \u0026#34;--serial\u0026#34;, \u0026#34;${file}\u0026#34; ], \u0026#34;outputCapture\u0026#34;: \u0026#34;std\u0026#34;, \u0026#34;skipFiles\u0026#34;: [ \u0026#34;\u0026lt;node_internals\u0026gt;/**/*.js\u0026#34; ] } ","permalink":"https://bynaki.github.io/posts/ava.debugging-vscode/","summary":"Debugging tests with Visual Studio Code\nYou can debug your tests using Visual Studio Code.\nDebugging with the debug terminal You can use VS Code\u0026rsquo;s “JavaScript Debug Terminal” to automatically debug AVA run on the command-line.\n From the Command Palette (F1or command + shift + p/ control + shift + p), run Debug: Create JavaScript Debug Terminal Run npx ava in the terminal  Creating a launch configuration Alternatively you can create a launch configuration, which makes it easier to debug individual test files.","title":"Ava :: Debugging tests with Visual Studio Code"}]