- 投稿日:2020-09-07T23:41:38+09:00
Node.jsのHTTPクライアントまとめ
概要
2020/2にNode.jsのrequestモジュールがDeprecated(非推奨)になってしまいました。
https://qiita.com/kE-sakai/items/1a64462ad41c36813c92そこで複数の代替モジュールについて各種比較サイトを調べてまとめました。
モジュール名 優位性[参照サイトNo] node-fetch バンドルサイズが小さい[1]
ダウンロード数が多い[2]axios GitHub starsが多い[3] got 全体ポイントが高い[5] bent APIスタイルが多い[1] superagent バージョンが多い[5]
メンテナーが多い[5]ky インストールサイズが小さい[3] Reqwest 依存関係が少ない[5] make-fetch-happen unfetch tiny-json-http needle urllib 参照サイト
1. Alternative libraries to request
https://github.com/request/request/issues/3143
スレッド形式。モジュール数が多い。2. npm trends
https://www.npmtrends.com/node-fetch-vs-bent-vs-got-vs-make-fetch-happen-vs-axios-vs-superagent-vs-fetch-vs-unfetch-vs-tiny-json-http-vs-needle
グラフ形式。ダウンロード数が時系列で見れる。3. got#comparison
https://github.com/sindresorhus/got#comparison
表形式。各種特徴について細かく比較されている。4. Request is going into maintenance mode, this is what you need to know
https://nodesource.com/blog/express-going-into-maintenance-mode
文章形式。使い方や特徴が書いてある。5. NPMCompare
https://npmcompare.com/compare/axios,got,request,reqwest,superagent
表形式。総合的に評価して全体ポイントを出している。
- 投稿日:2020-09-07T23:41:38+09:00
Node.jsのHTTPクライアントまとめ2020
概要
2020/2にNode.jsのrequestモジュールがDeprecated(非推奨)になってしまいました。
https://qiita.com/kE-sakai/items/1a64462ad41c36813c92そこで複数の代替モジュールについて各種比較サイトを調べてまとめました。
モジュール名 定量的な優位性[参照サイトNo] node-fetch バンドルサイズが小さい[1]
ダウンロード数が多い[2]axios GitHub starsが多い[3] bent APIスタイルが多い[1]
アップデートが頻繁[5]superagent メンテナーが多い[5] ky インストールサイズが小さい[3] got make-fetch-happen unfetch tiny-json-http needle urllib 参照サイト
1. Alternative libraries to request
https://github.com/request/request/issues/3143
スレッド形式。モジュール数が多い。2. npm trends
https://www.npmtrends.com/node-fetch-vs-bent-vs-got-vs-make-fetch-happen-vs-axios-vs-superagent-vs-fetch-vs-unfetch-vs-tiny-json-http-vs-needle
グラフ形式。ダウンロード数が時系列で見れる。3. got#comparison
https://github.com/sindresorhus/got#comparison
表形式。各種特徴について細かく比較されている。4. Request is going into maintenance mode, this is what you need to know
https://nodesource.com/blog/express-going-into-maintenance-mode
文章形式。使い方や特徴が書いてある。5. NPMCompare
https://npmcompare.com/compare/axios,bent,got,node-fetch,superagent
表形式。総合的に評価して全体ポイントを出している。まとめ
総合的には参照サイト5のように、node-fetchが一番優位性があるように感じました。
- 投稿日:2020-09-07T23:24:21+09:00
AWSLambda(Node.js)の入力パラメータチェック(バリデーション)
AWSLambda(Node.js)のREST APIにおいて入力パラメータのチェックがしたい
そうだ、value-schemaを使おうvalue-schemaができること
1.必須パラメータの有無、
2.型、
3.想定範囲内に存在するか(e.g.limit < input < limit)、
上記3点における入力パラメータの検証と修正ができる使い方
大きく2つの書き方がある....と勝手に思ってる
基本のフォーマットは vs.型名( {オプション} )//====その1. オブジェクトの中身をまとめてチェックする方法==== var vs = require("value-schema"); // 入力パラメータのオブジェクト let requestbody = { testId: "test", testNum: 1, testlist: [1, 2, 3], NoCheckid:"no", }; // 入力パラメータの満たすべき条件 const schemaObject = { testId: vs.string({minLength: 3}), //eventIdが文字列かつ5文字以上 testNum: vs.number({minValue: 1,}), //testNumが数字かつ1以上 testlist: vs.array({minLength: 2}), //testlistがarrayかつ2要素以上 //noNoCheckidは条件を書いてないのでチェックされない }; // 全ての条件を満たさない場合エラーを投げる,満たす場合は変数にいれる const checkedRequestbody = vs.applySchemaObject(schemaObject,requestbody,(err)=> { throw new Error("入力パラメータがおかしい") });//====その2. パラメータ単体でチェックする方法==== var vs = require("value-schema"); const flag = true; const checkedName = vs.boolean().applyTo(flag,(err)=> { //flagがbool値である throw new Error("入力flagがおかしい") //条件を見たさない場合err投げる });ほぼ全ての型で使える便利なオプション
{strictType: true} : 厳密なタイプチェックができる、デフォルトはオフ
{ifUndefined: somevalue} : パラメータがundefinedの場合に任意の値を入れておく
{ifNull: somevalue} : パラメータがnullの場合に任意の値を入れておく
{ifEmptyString: somevalue} : パラメータが空文字""の場合に任意の値を入れておく*その他オプションなどは公式を参照
- 投稿日:2020-09-07T23:24:21+09:00
AWSLambda(Node.js)の入力パラメータチェック
AWSLambda(Node.js)のREST APIにおいて入力パラメータのチェックがしたい
そうだ、value-schemaを使おうvalue-schemaができること
1.必須パラメータの有無、
2.型、
3.想定範囲内に存在するか(e.g.limit < input < limit)、
上記3点における入力パラメータの検証と修正ができる使い方
大きく2つの書き方がある....と勝手に思ってる
基本のフォーマットは vs.型名( {オプション} )//====その1. オブジェクトの中身をまとめてチェックする方法==== var vs = require("value-schema"); // 入力パラメータのオブジェクト let requestbody = { testId: "test", testNum: 1, testlist: [1, 2, 3], NoCheckid:"no", }; // 入力パラメータの満たすべき条件 const schemaObject = { testId: vs.string({minLength: 3}), //eventIdが文字列かつ5文字以上 testNum: vs.number({minValue: 1,}), //testNumが数字かつ1以上 testlist: vs.array({minLength: 2}), //testlistがarrayかつ2要素以上 //noNoCheckidは条件を書いてないのでチェックされない }; // 全ての条件を満たさない場合エラーを投げる,満たす場合は変数にいれる const checkedRequestbody = vs.applySchemaObject(schemaObject,requestbody,(err)=> { throw new Error("入力パラメータがおかしい") });//====その2. パラメータ単体でチェックする方法==== var vs = require("value-schema"); const flag = true; const checkedName = vs.boolean().applyTo(flag,(err)=> { //flagがbool値である throw new Error("入力flagがおかしい") //条件を見たさない場合err投げる });ほぼ全ての型で使える便利なオプション
{strictType: true} : 厳密なタイプチェックができる、デフォルトはオフ
{ifUndefined: somevalue} : パラメータがundefinedの場合に任意の値を入れておく
{ifNull: somevalue} : パラメータがnullの場合に任意の値を入れておく
{ifEmptyString: somevalue} : パラメータが空文字""の場合に任意の値を入れておく*その他オプションなどは公式を参照
- 投稿日:2020-09-07T23:14:58+09:00
Reactでnpm startができなくなった話。
React.js Node.js環境でnpm start実行時にエラー発生。
解決策だけ見たい人は最後に載せてます。(予定)
問題編
【React】いまどきのJSプログラマーのためのNode.jsとReactアプリケーション開発テクニックという参考書
の写本・実践をやっていると、
React.js Node.js環境でnpm startできなくなった。
経緯編
create-react-appでreactのアプリを作った。
app.jsを編集し、いざ起動する。
npm startそうすると、以下のようなエラーが発生。
> cycle@0.1.0 start /Users/user/Documents/ubuntu/cycle > react-scripts start There might be a problem with the project dependency tree. It is likely not a bug in Create React App, but something you need to fix locally. The react-scripts package provided by Create React App requires a dependency: "webpack": "4.42.0" Don't try to install it manually: your package manager does it automatically. However, a different version of webpack was detected higher up in the tree: /Users/user/Documents/ubuntu/node_modules/webpack (version: 4.44.1) Manually installing incompatible versions is known to cause hard-to-debug issues. If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That will permanently disable this message but you might encounter other issues. To fix the dependency tree, try following the steps below in the exact order: 1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder. 2. Delete node_modules in your project folder. 3. Remove "webpack" from dependencies and/or devDependencies in the package.json file in your project folder. 4. Run npm install or yarn, depending on the package manager you use. In most cases, this should be enough to fix the problem. If this has not helped, there are a few other things you can try: 5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead. This may help because npm has known issues with package hoisting which may get resolved in future versions. 6. Check if /Users/user/Documents/ubuntu/node_modules/webpack is outside your project directory. For example, you might have accidentally installed something in your home folder. 7. Try running npm ls webpack in your project folder. This will tell you which other package (apart from the expected react-scripts) installed webpack. If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That would permanently disable this preflight check in case you want to proceed anyway. P.S. We know this message is long but please read the steps above :-) We hope you find them helpful! npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! cycle@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the cycle@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/user/.npm/_logs/2020-09-07T13_28_49_449Z-debug.log (base) user-no-MacBook-Air:cycle user$ SKIP_PREFLIGHT_CHECK=true npm start > cycle@0.1.0 start /Users/user/Documents/ubuntu/cycle > react-scripts start Attempting to bind to HOST environment variable: x86_64-apple-darwin13.4.0 If this was unintentional, check that you haven't mistakenly set it in your shell. Learn more here: https://bit.ly/CRA-advanced-config dyld: lazy symbol binding failed: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace dyld: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! cycle@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the cycle@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/user/.npm/_logs/2020-09-07T13_29_11_414Z-debug.log (base) user-no-MacBook-Air:cycle user$ eact-scripts start -bash: eact-scripts: command not found (base) user-no-MacBook-Air:cycle user$ react-scripts start There might be a problem with the project dependency tree. It is likely not a bug in Create React App, but something you need to fix locally. The react-scripts package provided by Create React App requires a dependency: "webpack": "4.42.0" Don't try to install it manually: your package manager does it automatically. However, a different version of webpack was detected higher up in the tree: /Users/user/Documents/ubuntu/node_modules/webpack (version: 4.44.1) Manually installing incompatible versions is known to cause hard-to-debug issues. If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That will permanently disable this message but you might encounter other issues. To fix the dependency tree, try following the steps below in the exact order: 1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder. 2. Delete node_modules in your project folder. 3. Remove "webpack" from dependencies and/or devDependencies in the package.json file in your project folder. 4. Run npm install or yarn, depending on the package manager you use. In most cases, this should be enough to fix the problem. If this has not helped, there are a few other things you can try: 5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead. This may help because npm has known issues with package hoisting which may get resolved in future versions. 6. Check if /Users/user/Documents/ubuntu/node_modules/webpack is outside your project directory. For example, you might have accidentally installed something in your home folder. 7. Try running npm ls webpack in your project folder. This will tell you which other package (apart from the expected react-scripts) installed webpack. If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That would permanently disable this preflight check in case you want to proceed anyway. P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!検索すると、
SKIP_PREFLIGHT_CHECK=trueを.envファイルに記載すると良いと出てきた。(勘違いかも。。)
だが、まずcreate-react-appで作ったアプリのフォルダ内に.envファイルが見つからない。。。
どうしようと悩み、調べ続けるとnpm startの後に、直接打てば良いのでは? との記事を発見。。
試してみる。
SKIP_PREFLIGHT_CHECK=true npm start結果。
> cycle@0.1.0 start /Users/user/Documents/ubuntu/cycle > react-scripts start Attempting to bind to HOST environment variable: x86_64-apple-darwin13.4.0 If this was unintentional, check that you haven't mistakenly set it in your shell. Learn more here: https://bit.ly/CRA-advanced-config dyld: lazy symbol binding failed: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace dyld: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! cycle@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the cycle@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/user/.npm/_logs/2020-09-07T13_29_11_414Z-debug.log (base) user-no-MacBook-Air:cycle user$ eact-scripts start -bash: eact-scripts: command not found (base) user-no-MacBook-Air:cycle user$ react-scripts start There might be a problem with the project dependency tree. It is likely not a bug in Create React App, but something you need to fix locally. The react-scripts package provided by Create React App requires a dependency: "webpack": "4.42.0" Don't try to install it manually: your package manager does it automatically. However, a different version of webpack was detected higher up in the tree: /Users/user/Documents/ubuntu/node_modules/webpack (version: 4.44.1) Manually installing incompatible versions is known to cause hard-to-debug issues. If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That will permanently disable this message but you might encounter other issues. To fix the dependency tree, try following the steps below in the exact order: 1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder. 2. Delete node_modules in your project folder. 3. Remove "webpack" from dependencies and/or devDependencies in the package.json file in your project folder. 4. Run npm install or yarn, depending on the package manager you use. In most cases, this should be enough to fix the problem. If this has not helped, there are a few other things you can try: 5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead. This may help because npm has known issues with package hoisting which may get resolved in future versions. 6. Check if /Users/user/Documents/ubuntu/node_modules/webpack is outside your project directory. For example, you might have accidentally installed something in your home folder. 7. Try running npm ls webpack in your project folder. This will tell you which other package (apart from the expected react-scripts) installed webpack. If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project. That would permanently disable this preflight check in case you want to proceed anyway. P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!んーうまくいかない。。。。
さらに調べる。
そうすると、今度はホームディレクトリのnode_modulesを全削除すればうまくいくとの記事を発見。
試してみる。
create-react-appで作った該当node_modulesのみ、一時名前を変えて退避。
そして、それ以外のnode_modulesをホームに戻って全削除。
以下全削除のcommand
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +そして、create-react-appで作ったアプリのディレクトリに戻って、npm startを再度実行。
またエラーになった。
でもエラー文は変わった。
> cycle@0.1.0 start /Users/user/Documents/ubuntu/cycle > react-scripts start internal/modules/cjs/loader.js:895 throw err; ^ Error: Cannot find module 'entities/maps/entities.json' Require stack: - /Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/Tokenizer.js - /Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/Parser.js - /Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/index.js - /Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/tools.js - /Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/renderKid/styleApplier/inline.js - /Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/RenderKid.js - /Users/user/Documents/ubuntu/cycle/node_modules/pretty-error/lib/PrettyError.js - /Users/user/Documents/ubuntu/cycle/node_modules/html-webpack-plugin/lib/errors.js - /Users/user/Documents/ubuntu/cycle/node_modules/html-webpack-plugin/index.js - /Users/user/Documents/ubuntu/cycle/node_modules/react-scripts/config/webpack.config.js - /Users/user/Documents/ubuntu/cycle/node_modules/react-scripts/scripts/start.js at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15) at Function.Module._load (internal/modules/cjs/loader.js:742:27) at Module.require (internal/modules/cjs/loader.js:964:19) at require (internal/modules/cjs/helpers.js:88:18) at Object.<anonymous> (/Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/Tokenizer.js:4:17) at Module._compile (internal/modules/cjs/loader.js:1075:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1096:10) at Module.load (internal/modules/cjs/loader.js:940:32) at Function.Module._load (internal/modules/cjs/loader.js:781:14) at Module.require (internal/modules/cjs/loader.js:964:19) { code: 'MODULE_NOT_FOUND', requireStack: [ '/Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/Tokenizer.js', '/Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/Parser.js', '/Users/user/Documents/ubuntu/cycle/node_modules/htmlparser2/lib/index.js', '/Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/tools.js', '/Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/renderKid/styleApplier/inline.js', '/Users/user/Documents/ubuntu/cycle/node_modules/renderkid/lib/RenderKid.js', '/Users/user/Documents/ubuntu/cycle/node_modules/pretty-error/lib/PrettyError.js', '/Users/user/Documents/ubuntu/cycle/node_modules/html-webpack-plugin/lib/errors.js', '/Users/user/Documents/ubuntu/cycle/node_modules/html-webpack-plugin/index.js', '/Users/user/Documents/ubuntu/cycle/node_modules/react-scripts/config/webpack.config.js', '/Users/user/Documents/ubuntu/cycle/node_modules/react-scripts/scripts/start.js' ] } npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! cycle@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the cycle@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/user/.npm/_logs/2020-09-07T13_38_20_165Z-debug.logエラー文のいかに注目。。。
Error: Cannot find module 'entities/maps/entities.json'
このエラー文で検索をかけると、
install entities: npm i entities create a new index.js file with: require("entities/maps/entities.json") run itとすれば良いのでは? との記事を発見。
実行してみる。
結果。
> cycle@0.1.0 start /Users/user/Documents/ubuntu/cycle > react-scripts start Attempting to bind to HOST environment variable: x86_64-apple-darwin13.4.0 If this was unintentional, check that you haven't mistakenly set it in your shell. Learn more here: https://bit.ly/CRA-advanced-config dyld: lazy symbol binding failed: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace dyld: Symbol not found: _FSEventStreamCreate Referenced from: /Users/user/Documents/ubuntu/cycle/node_modules/webpack-dev-server/node_modules/fsevents/build/Release/fse.node Expected in: flat namespace npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! cycle@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the cycle@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/user/.npm/_logs/2020-09-07T22_44_27_537Z-debug.logまた別のエラー。。。
はぁ。。。
エラー文のなかで、
Attempting to bind to HOST environment variable: x86_64-apple-darwin13.4.0 If this was unintentional, check that you haven't mistakenly set it in your shell.に注目し、このエラー文で検索をかける。
そうすると、原因が
「HOST環境変数にバインドしようとしています:x86_64-apple-darwin13.4.0
これが意図的でない場合は、誤ってシェルに設定していないことを確認してください。」らしい。
HostをBindから解放するには
unset HOSTをすれば良いらしい。
実行。
エラー消えた!!!!
解決編
以下僕の場合の解決手順
ホームディレクトリのnode_modulesを全削除(create-react-appで作ったディレクトリのnode_modulesを除く。)
entitiesのinstall
HostのBindからの解放
以下実際のコマンド
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +install entities: npm i entities create a new index.js file with: require("entities/maps/entities.json") run itunset HOST参考文献
https://teratail.com/questions/177560
https://qiita.com/yuta0801/items/118d9478ad536a443f3f
https://mebee.info/2020/03/03/post-6791/
https://github.com/davideicardi/live-plugin-manager/issues/14
- 投稿日:2020-09-07T22:24:51+09:00
クジラとネコの親子プログラミング - Docker for Windowsを使ってScratch3.0のオリジナル拡張機能を試してみよう。
親子プログラミングはGitとNode.jsが使えることが前提になっている?
小学校でのプログラミング教育の必須化に伴って、子供たちがScratch 3.0に触れる機会も増えるかと思います。そんな中、ブロックをくっつけるだけのお遊びツールだとあなどっていると、次のような連載が始まりました。
「親子でできる!Scratch と AWS を使った "ものづくり" 体験 - 1. 準備 〜 疎通確認編」
2020-09-01
How to be a Developer
金澤 圭この連載の「2. 作業の前提について」で、衝撃的な次の一文があります。
PC に Git と Node.js がインストールされている必要があります。
保護者の方も、GitやNode.jsを当たり前のようにインストールしなければいけない時代になりましたね。でも、安心してください。Dockerという便利なツールがありますので、簡単に開発環境を整えることができます。
本記事では、Webベースの統合開発環境である
code-server
とScratch 3.0 拡張機能の開発と実行に必要なソースコード(scratch-vm/scratch-gui
)を詰め合わせたDockerコンテナ(jprad/s3coder
)を使って、Windowsパソコン上で、Scratch 3.0 GUI
サーバーを起動できるようにします。
後半では、「Scratch 3.0の拡張機能を作ってみよう」を参考にして、拡張機能を追加します。拡張機能を追加して、Scratch 3.0 GUIでコーディング
必要なもの
- Windows 10 パソコン
- Docker Desktop on Windows または Docker Desktop on Windows Home
Windows 10 パソコンにDockerをインストールしてください。Dockerのインストール方法は、リンク先や各種記事を参照してください。
セットアップと起動
Dockerイメージ(
jprad/s3coder
)を元にDockerコンテナを起動し、Scratch 3.0 GUI
サーバーをWindowパソコンで実行できるようにします。1. 共有フォルダの作成とDockerコンテナの初回起動
Windows 10 で、コマンドプロンプトを起動し、次の一連のコマンドを入力します。
コマンドプロンプト.cmdcd c:\ mkdir scratch-ws docker run --name s3coder -d -p 8080:8080 -p 8601:8601 ^ -v C:/scratch-ws:/home/coder/s3/scratch-ws -e PASSWORD=password ^ jprad/s3coder /home/coder/s3 REM docker run ... のコマンドが長いので「^(キャレット)」で改行しています。
C\scratch-ws
フォルダは、Dockerコンテナにマウントされる共有フォルダです(/home/coder/s3/scratch-ws)。
docker run
コマンドを開始すると、必要なDockerイメージ(合計:844.17 MB)のダウンロードが始まり、Dockerコンテナが起動されます(コンテナ名:s3coder
)。Dockerコンテナの初回起動時に、共有フォルダへのアクセスを許可するかどうかの確認通知が表示されますので、
[Share it]
で許可します。2.code-severへのログインとScratch 3.0 GUIの起動
Dockerコンテナの起動完了後、
code-server
( http://localhost:8080 ) へアクセスし、ログインします(パスワードは、password
です)。統合開発環境が開きますので、Dockerイメージに同梱されているscratch-gui
を起動します。起動方法が構成ファイル(./s3/.vscode/launch.json)に設定されていますので、クリック操作のみで起動できます。scratch-gui
の起動完了後、Scratch 3.0 GUI
( http://localhost:8601 ) へアクセスすると、公式ページとは少しばかり異なっていますが、使い慣れたScratch 3.0
でのコーディングが行えます。手順
1.code-server
( http://localhost:8080 ) へアクセスする。
2. パスワードにpassword
と入力し、[SUBMIT]
ボタンをクリックし、ログインする。
3.[Run (Ctrl + Shift + D)]
アイコンをクリックする。
4. ドロップダウンリストで'Run Scratch 3.0 GUI'
(既定)を選択する。
5.[Start Debuging]
アイコンをクリックする。
6.[TERMINAL]
タブをクリックし、ビルド完了後の'Compiled successfully'
が表示されるのを待つ。
7.Scratch 3.0 GUI
( http://localhost:8601 ) へアクセスする。3.停止・再開
scratch-guiの再開・停止
scratch-guiを停止せずに再開するには、coder-serverの[Restart (Ctrl+Shift+F5)]
アイコンをクリックします。
scratch-guiを停止するには、code-serverの[Stop (Shift+F5)]
アイコンをクリックします。scratch-guiの開始
[Run (Ctrl + Shift + D)]
アイコンをクリックする。- ドロップダウンリストで
'Run Scratch 3.0 GUI'
(既定)を選択する。[Start Debuging]
アイコンをクリックする。[TERMINAL]
タブをクリックし、ビルド完了後の'Compiled successfully'
が表示されるのを待つ。Dockerコンテナの停止
コマンドプロンプトで次のコマンドを実行するとDockerコンテナ(コンテナ名:s3coder
)が停止します。コマンドプロンプト.cmddocker stop s3coderDockerコンテナの再開
コマンドプロンプトで次のコマンドを実行するとDockerコンテナ(コンテナ名:s3coder
)が再開します。コマンドプロンプト.cmddocker start s3coder拡張機能の開発
Scratch 3.0 Extensions の開発に関する情報には、次のようなものがあります。
- 「子供の科学 2020年9月号, p.p.66-69, ジャバスクリプトでスクラッチを拡張しよう」
子供向けの月刊誌の記事です。- 「Scratch を改造しよう」
Strecth3として、Scratch3.0で機械学習をプログラミングできる開発環境を提供する石原 淳也(いしはら じゅんや)氏の有償コンテンツです(一部無料公開あり)。- 「Scratch 3.0 Extensions」
LLK公式の拡張機能に関するページです。- 「Scratch 3.0の拡張機能を作ってみよう」
Scratch 3.0の拡張機能の作り方をその下準備から説明しています。ここでは、「Scratch 3.0の拡張機能を作ってみよう」を参考にログを出力する拡張機能(ブロック)を実装(コピペ)してみます。
拡張機能に必要なファイル
拡張機能(
s3coder_newblocks
)を実装するには、次のファイルを追加・編集します。scratch-vm
# フォルダ ファイル 追加 編集 説明 1 scratch-vm/src/extensions/s3coder_newblocks index.js 〇 拡張機能( newblocks
)の本体です。2 scratch-vm/src/extension-support extension-manager.js 〇 追加した拡張機能( s3coder_newblocks
)をbuiltinExtensions
に追加登録します。scratch-gui
# フォルダ ファイル 追加 編集 説明 1 scratch-gui/src/lib/libraries/extensions/s3coder_newblocks newblocks.png 〇 600x372ピクセルのPNG形式ファイルです。拡張機能の選択時にバナーとして表示されます。 2 scratch-gui/src/lib/libraries/extensions/s3coder_newblocks newblocks-small.png 〇 80x80ピクセルのPNG形式ファイルです。ブロックのアイコンとして表示されます。 3 scratch-gui/src/lib/libraries/extensions index.js 〇 PNG形式ファイルの読込定義と拡張ブロックの定義を設定します。 scratch-vm での実装
scratch-vmで、拡張機能そのものを実装します。
フォルダ作成
拡張機能用のフォルダを次の手順で作成します。
code-server
のEXPLORERで、s3/scratch-vm/src/extensions
フォルダを選択します。- 右クリックで、コンテキストメニューから
New Folder
を選択し、's3coder_newblocks'
フォルダを作成します。index.jsファイルの実装
次の手順で、
index.js
ファイルを実装します。
- 作成した
's3coder_newblocks'
フォルダで右クリックし、New File
を選択し、ファイル名をindex.js
とします。- 「Scratch 3.0の拡張機能を作ってみよう/基本の書式 - 拡張機能の追加」から
index.js
のソースコードをコピー&ペーストします。
index.js
index.jsconst ArgumentType = require('../../extension-support/argument-type'); const BlockType = require('../../extension-support/block-type'); const Cast = require('../../util/cast'); const log = require('../../util/log'); /** * Icon svg to be displayed at the left edge of each extension block, encoded as a data URI. * @type {string} */ // eslint-disable-next-line max-len const blockIconURI = 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48ZyBpZD0iSUQwLjA4NjgyNDQzOTAwMDMzODMyIiB0cmFuc2Zvcm09Im1hdHJpeCgwLjQ5MTU0NjY2MDY2MTY5NzQsIDAsIDAsIDAuNDkxNTQ2NjYwNjYxNjk3NCwgLTY0LjUsIC03Ny4yNSkiPjxwYXRoIGlkPS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dHJpeCgxLCAwLCAwLCAxLCAtNTcsIDE1LjgpIi8+PHBhdGggaWQ9IklEMC4yNDM2NzMwNzMxMjc4NjU4IiBmaWxsPSJub25lIiBzdHJva2U9IiNGRkZGRkYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBkPSJNIDIyNyAxNTQgQyAyMjcgMTU0IDIxOC41NTUgMTQ3Ljg5MCAyMTcgMTUxIEMgMjEyLjM0NSAxNjAuMzEwIDIxMS4yODkgMTcxLjczMyAyMTMgMTgyIEMgMjEzLjYxMiAxODUuNjcyIDIyMyAxODcgMjIzIDE4NyAiIHRyYW5zZm9ybT0ibWF0cml4KDEsIDAsIDAsIDEsIC01NywgMTUuOCkiLz48cGF0aCBpZD0iSUQwLjc5MzkzOTQ4MTk1NTAyMTYiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIGQ9Ik0gMTc1IDIwMC41MDAgQyAxNzUgMjAwLjUwMCAxNjkuODA1IDIyMS45MTMgMTcxIDIyMi43NTAgQyAxNzIuMTk1IDIyMy41ODcgMTc4Ljc5NSAyMDUuMjk1IDE4Mi41MDAgMjA1Ljc1MCBDIDE4NS45MjAgMjA2LjE3MCAxODEuODU5IDIyNC41MDAgMTg1LjI1MCAyMjQuNTAwIEMgMTg5LjIxMyAyMjQuNTAwIDE5Ny4yNTAgMjA1Ljc1MCAxOTcuMjUwIDIwNS43NTAgIi8+PC9nPjwvc3ZnPg=='; /** * Icon svg to be displayed in the category menu, encoded as a data URI. * @type {string} */ // eslint-disable-next-line max-len const menuIconURI = 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOn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/** * Class for the new blocks in Scratch 3.0 * @param {Runtime} runtime - the runtime instantiating this block package. * @constructor */ class Scratch3NewBlocks { constructor (runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; //this._onTargetCreated = this._onTargetCreated.bind(this); //this.runtime.on('targetWasCreated', this._onTargetCreated); } /** * @returns {object} metadata for this extension and its blocks. */ getInfo () { return { id: 'newblocks', name: 'New Blocks', menuIconURI: menuIconURI, blockIconURI: blockIconURI, blocks: [ { opcode: 'writeLog', blockType: BlockType.COMMAND, text: 'log [TEXT]', arguments: { TEXT: { type: ArgumentType.STRING, defaultValue: "hello" } } }, { opcode: 'getBrowser', text: 'browser', blockType: BlockType.REPORTER } ], menus: { } }; } /** * Write log. * @param {object} args - the block arguments. * @property {number} TEXT - the text. */ writeLog (args) { const text = Cast.toString(args.TEXT); log.log(text); } /** * Get the browser. * @return {number} - the user agent. */ getBrowser () { return navigator.userAgent; } } module.exports = Scratch3NewBlocks;extension-manager.jsファイルの変更
scratch-vm/src/extension-support
フォルダのextension-manager.js
ファイルを開き、builtinExtensions
に、次のように拡張機能(s3coder_newblocks
)を追加登録します。
※カンマで区切ることを忘れないでください。extension-manager.jsconst builtinExtensions = { ... gdxfor: () => require('../extensions/scratch3_gdx_for'), newblocks: () => require('../extensions/s3coder_newblocks'), };scratch-gui での設定
scratch-guiで、拡張機能を選択できるように設定します。
フォルダ作成
画像保存用のフォルダを次の手順で作成します。
code-server
のEXPLORERで、s3/scratch-gui/src/lib/libraries/extensions
フォルダを選択します。- 右クリックで、コンテキストメニューから
New Folder
を選択し、's3coder_newblocks'
フォルダを作成します。画像ファイル
画像ファイルをダウンロードし、作成したフォルダへ保存します。
- 2つの画像ファイルをダウンロードし、
C:\scratch-ws
フォルダへ保存します。code-server
のEXPLORERで、s3/scratch-ws
フォルダを開き、2つの画像ファイルを選択し、右クリックでコンテキストメニューからCopy
します。s3/scratch-gui/src/lib/libraries/extensions/s3coder_newblocks
フォルダを選択し、右クリックでコンテキストメニューからPaste
します。index.jsファイルの設定
s3/scratch-gui/src/lib/libraries/extensions
フォルダのindex.js
ファイルを開き、次のように拡張機能の設定を行います。これにより、Scratch 3.0 GUI
の拡張機能の追加で、拡張機能を選択できるようになります。index.js... import gdxforConnectionSmallIconURL from './gdxfor/gdxfor-small.svg'; import newblocksImage from './s3coder_newblocks/newblocks.png'; import newblocksInsetImage from './s3coder_newblocks/newblocks-small.png'; export default [ ... ), helpLink: 'https://scratch.mit.edu/vernier' }, { name: ( <FormattedMessage defaultMessage="New Blocks" description="Name for the 'New Blocks' extension" id="gui.extension.newblocks.name" /> ), extensionId: 'newblocks', iconURL: newblocksImage, insetIconURL: newblocksInsetImage, description: ( <FormattedMessage defaultMessage="New extension" description="Description for the 'New Blocks' extension" id="gui.extension.newblocks.description" /> ), featured: true }, ];動作確認
scratch-gui
を開始し、Scratch 3.0 GUI
を開きなおすと、「拡張機能を追加」で、新しい拡張機能を選択できます。
logブロック
を実行すると、ブラウザのConsoleにhello
と出力されます。おわりに
- Dockerイメージ(jprad/s3coder)を使って、Scratch 3.0 Extentionsの開発環境と動作環境を構築しました。
- 「Scratch 3.0の拡張機能を作ってみよう」を参考にして、拡張機能を追加しました。
【メモ】Dockerイメージの作成
dos.cmdcd c:\ mkdir scratch-ws docker run -it -p 8080:8080 -p 8601:8601 -v C:/scratch-ws:/home/coder/s3/scratch-ws -e PASSWORD=password codercom/code-server /home/coder/s3http://localhost:8080/ へアクセス
sudo apt-get update -y sudo apt-get install -y nodejs npm sudo npm install -g npmsudo chown -R coder:coder /home/coder/s3 git clone --depth 1 https://github.com/llk/scratch-vm.git git clone --depth 1 https://github.com/llk/scratch-gui.git cd scratch-vm npm ci sudo npm link cd ../scratch-gui npm ci sudo npm link scratch-vmnpm start --->> [Ctrl]+[C]で中断http://localhost:8601/ へアクセス
- scratch-guiのポート
ENV環境変数で設定可能Dockerfile の記述
docker build -t test-image . docker run --name test-container -it -p 8080:8080 -p 8601:8601 -v C:/scratch-ws:/home/coder/s3/scratch-ws -e PASSWORD=password test-image /home/coder/s3
- 投稿日:2020-09-07T22:13:05+09:00
stdout is not a ttyに叱られる
完全に自分用の健忘録です
Git Bash(ver2.28)で実行しようとした際に、
$ node hogehuga.js stdout is not a ttyと叱られてしまった。悲しい。
原因はMinTTYのアレです。大体winptyを先頭につければ解決すると思ってたけど、今回は解決しなかった。
Gitを再インストールしてもダメ。5分くらい悩んで、拡張子をつけたら動いた。
$ node.exe hogehuga.js以下参考
https://github.com/mintty/mintty/wiki/Tips#inputoutput-interaction-with-alien-programs
- 投稿日:2020-09-07T17:50:39+09:00
node環境でのmysql
nodejs環境でmysqlを使用する方法
mysqlインスタンスの作成
const mysql = require('mysql') const connection = mysql.createPool({ host: 'localhost', user: 'root', password: 'secret', database: 'my_db' })データの参照
select文
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function(error, results, fields){ //error: クエリ実行時にエラーが発生したらエラーオブジェクトを持つ //results: クエリの実行結果を持つ //fields: クエリ実行結果のフィールドに関するオブジェクト })データの挿入
insert文
connection.query('INSERT INTO `books` SET ?', data, function(error, results, fields){ //error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ //results:クエリの実行結果を持つ //fields:クエリ実行結果のフィールドに関するオブジェクト })データの更新
update文
connection.query('UPDATE `books` SET カラム名 = ? WHERE id = ?, ['name', 3], function(error, results, field){ //error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ //results:クエリの実行結果を持つ //fields:クエリ実行結果のフィールドに関するオブジェクト })データの削除
delete文
connection.query('DELETE FROM `books` WHERE id = ?', [3], function(error, results, fields){ //error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ //results:クエリの実行結果を持つ //fields:クエリ実行結果のフィールドに関するオブジェクト })