20211025のNode.jsに関する記事は6件です。

detaにNodeJSで入門(ほぼ自分用メモ)

deta (baas) なんかこれが欲しかったけど今まではなかったもの感が否めない最高なBaas(?)。 無料&クレカなし&簡単。満足。最高。 データベース(NoSQL) Faas (lambdaとかFirebase functions みたいなやつ) ストレージ これらが本当にお手軽に使える。 大切なことなのでもう一度言う。 本当にお手軽に使える。 インストールもろもろ CLIインストール # Windowsの方 (PowerShellで実行してください!) iwr https://get.deta.dev/cli.ps1 -useb | iex # macの方 curl -fsSL https://get.deta.dev/cli.sh | sh 自分はWindowsユーザなのでmacは試せていません。エラーなどあったらごめんなさい。 パッケージインストール npm init -y yarn add deta 共通部分 いろいろインポートしておく。 const { Deta } = require("deta") ; const deta = Deta(process.env.DETA_PROJECT_KEY) ; micro Faas,瞬時的なクラウド上の実行環境 いろいろセットアップ microは別プロジェクトで立ち上げるか、トップフォルダ直下にプロジェクト作るほうがよさそう deta new --node プロジェクト名 コード const express = require('express') const app = express() app.get('/', (req, res) => { const reqBody = req.body ; res.status(200).json({ msg:"ok", reqBody, }); }) ; module.exports = app ; base DBaas,データベース const usersDb = deta.Base("users") ; //async 関数内で実行 usersDb.put( { name:"TBSten", job:"エンジニア", } ); const userList = await usersDb.fetch() ; userList.items.forEach(el=>{ console.log(el); }); Drive Storage,10GBくらいおけるらしい const photos = deta.Drive("photos") ; //async 関数内で実行 await photos.put( "test.png", {path: "test/GitHub-Mark.png"} ) ; 個人的にはこんなフォルダ構成で使いそう lib/ +- deta/ +-deta.js //detaをエクスポート +-base.js //deta.jsのdetaからbaseと各テーブルをエクスポート +-drive.js //deta.jsのdetaからdriveと各フォルダをエクスポート +- +- ...(自作ライブラリなど)... server/ +- node_module/ +- ... +- index.js //expressでルート分岐 参考サイト 公式ドキュメント(英語だけどほんやくしたら結構読める) 独り言 欲しい機能がこれでもかとあるので、今後作ろうとしているサービスで採用予定です。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

TeamViewer IoTのAPIをNode.jsから触ってみたメモ #iotlt

LTネタとして1時間くらい調べたくらいの雑観です。時間かけてないので間違いが多いかもしれません。 TeamViewer IoTってサービスがあるんですね、TeamViewerは学生時代にリモートデスクトップで使ったことあった気がする。そのソフトのIoT...?ほうほう。 IoTLTのグループでコメントをもらったので触ってみました。 ちなみに次回のIoTLTは11/16です! https://iotlt.connpass.com/event/228734/ また、こんなの作ったよー話はこちらのスライドに載ってます。 https://speakerdeck.com/n0bisuke2/teihuaruwang-rewen-ti-number-iotlt なんとなくの全体感 ラズパイなどにSDKを仕込んでデータをクラウドに上げる ダッシュボードなどの機能がある データをストアできる機能がある MQTTが使える 設定変更などをREST API経由で行える こんな感じのIoTのバックエンドサービスです。 サイト見ても料金などが見つけられなかったので無料プランと有料プランの違いみたいなのがいまいち把握できていません。 アカウント作成 せっかくなのでアカウント作成画面から、 「ほとんど終わりです!」、そっか! 独特な日本語訳だな。。。 何ができるか探す SDK色々ある模様。Node.jsを見つけてテンションが上がります。 ただラズパイなどに入れる想定っぽいのと通常のようにnpmに存在するわけではなさそうでした。 TeamViewer IoT Cloud API 1番サクッと使えそうだったTeamViewer IoT Cloud APIを触ってみました。 おそらくですがMQTTのトピックなどを作成したり、それらをグルーピングしたりが出来るAPIです。 とりあえずGET とりあえずドキュメントを上から見た時に最初にあったGet Assignment Tokenのエンドポイントを叩いてみます。 https://docs.teamviewer-iot.com/cloud-api/#11-get-assignment-token APIキーを指定してあげて、APIバージョンを指定すれば素直に動いてくれました。 APIバージョンは現時点だと2.0.0で固定文字列で問題なさそうです。 app.js 'use strict'; const axios = require(`axios`); const API_KEY = `xxxxx`; const API_VERSION = `2.0.0`; const URL = `https://api.teamviewer-iot.com/assignmentToken`; (async () => { const options = { headers: { Authorization: `Bearer ${API_KEY}`, Accept: `application/json; Version=${API_VERSION};` } } try { const res = await axios.get(URL, options); console.log(res.data); } catch (error) { console.log(error.response.data); } })(); $ node app.js { uid: 'u181744624', assignmentToken: '*', data: '14370533-ttNCDoiTeWFhitMfGCwz', status: 'OK', timestamp: 1634797986766 } 無事に結果が帰ってきました。 トピックの作成 トピックの作成が出来たので試してみました。 https://docs.teamviewer-iot.com/cloud-api/#101-create-topic 'use strict'; const axios = require(`axios`); const API_KEY = `xxxxxxxxxx`; const API_VERSION = `2.0.0`; const URL = `https://api.teamviewer-iot.com/topics`; (async () => { const body = { "action": "create", "payload": { "name": "n0bisuke-topic", "channels": [ "5d498a5a965e59417cb3cf36" ] } }; const options = { headers: { Authorization: `Bearer ${API_KEY}`, Accept: `application/json; Version=${API_VERSION};` }, } try { const res = await axios.post(URL, body, options); console.log(res.data); } catch (error) { console.log(error.response.data); } })(); リクエストBodyの部分はサンプルコードのままです。channelsのIDっぽいのは適当な数字 const body = { "action": "create", "payload": { "name": "n0bisuke-topic", //名前を変えてみた。 "channels": [ "5d498a5a965e59417cb3cf36" //サンプルのまま ] } }; 実行してみる $ node create_topic.js { uid: 'u181744624', body: { name: 'n0bisuke-topic', channels: [ '5d498a5a965e59417cb3cf36' ] }, data: { id: '61767fade27d3be61b9af5f6', info: 'InvalidChannelId(s): [5d498a5a965e59417cb3cf36]' }, topics: '*', status: 'OK', timestamp: 1635155885620 } トピックが作成されて、何かIDが取得出来ました。 トピックの情報を更新する 先ほど作成したトピックの情報を変更してみます。 https://docs.teamviewer-iot.com/cloud-api/#104-update-topic IDを指定してトピック名を変更してみます。 'use strict'; const axios = require(`axios`); const API_KEY = `xxxxxxxxxxxxxxx`; const API_VERSION = `2.0.0`; const URL = `https://api.teamviewer-iot.com/topics`; (async () => { const body = { action: `update`, payload: { id: `61710b40e27d3be61b9aeb81`, name: `hoge` } }; const options = { headers: { Authorization: `Bearer ${API_KEY}`, Accept: `application/json; Version=${API_VERSION};` }, } try { const res = await axios.post(URL, body, options); console.log(res.data); } catch (error) { console.log(error.response.data); } })(); これでトピック名がhogeになりました。 $ node update_topic.js { uid: 'u181744624', body: { name: 'hoge', id: '61710b40e27d3be61b9aeb81' }, data: { id: '61710b40e27d3be61b9aeb81', info: '' }, topics: '*', status: 'OK', timestamp: ふむふむ。トピックの名前がhogeになってますがidは引き継いでますね。 よもやま MQTTでトピックに情報をpublishしたいってのがありましたが、いまいちそこまで辿り着けてません。 感想など 中途半端ですが、トピック名を更新することができたので、ここにセンサーデータを入れ込むという間違った使い方をしてティファールの温度管理っぽいのをやってみました。 https://speakerdeck.com/n0bisuke2/teihuaruwang-rewen-ti-number-iotlt API自体は素直な感じですが、全体像としてはまだ掴み切れてません。 Firebaseみたいにデータストアと通信がいい感じにやれる何かだと嬉しいんですけど果たしてどうなのか。。 気になった人は触って教えてください笑
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

chrome-driver のアップデート

環境 $ node --version v15.3.0 $ npm list chromedriver app@1.0.0 ***\app └── chromedriver@2.46.0 Google Chrome バージョン: 95.0.4638.54(Official Build) (64 ビット) Selenium npm run e2e 実行時にエラーになる $ npm run e2e > app@1.0.0 e2e > node test/e2e/runner.js Starting selenium server... started - PID: 80376 [Login] Test Suite ====================== Running: Login { parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }. Error retrieving a new session from the selenium server Connection refused! Is selenium server started? { value: { message: 'session not created: Chrome version must be between 71 and 75\n' + ' (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.19042 x86_64) (WARNING: The server did not provide any stacktrace information)\n' + 'Command duration or timeout: 1.32 seconds\n' + "Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'\n" + "System info: host: 'LAPTOP-AM2Q1C5U', ip: '192.168.2.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '15.0.1'\n" + 'Driver info: driver.version: unknown', error: 'session not created' }, status: 33 } npm ERR! code 1 npm ERR! path ***\app npm ERR! command failed npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node test/e2e/runner.js npm ERR! A complete log of this run can be found in: npm ERR! ***\AppData\Local\npm-cache\_logs\2021-10-25T05_25_32_549Z-debug.log ※パスは *** でマスキング エラーメッセージの内容 session not created: Chrome version must be between 71 and 75 (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1) googe翻訳 セッションが作成されていません:Chromeのバージョンは71から75の間である必要があります (ドライバー情報:chromedriver = 2.46.628402(536cd7adbad73a3783fdc2cab92ab2ba7ec361e1) メッセージ的には「Chrome のバージョン合わせろ」と読めますが、ダウングレードはしたくないので、chrome-driver をアップデートする事にする アップデートされない Chrome Driver NPM | npm.io を参考に、アップデートを実行する。その後、npm list chromedriver でバージョン確認したが、アップデートされない。 $ npm list chromedriver app@1.0.0 ***\app └── chromedriver@2.46.0 $ npm install --save-dev chromedriver --chromedriver_version=LATEST $ npm list chromedriver app@1.0.0 ***\app └── chromedriver@2.46.0 結論 インストール済みの chrome-driver を削除後、chrome-driver の最新版をインストールする # chrome-driver の削除 $ npm rm --save-dev chromedriver # chrome-driver のインストール $ npm install --save-dev chromedriver --chromedriver_version=LATEST # chrome-driver があるか確認 $ npm list chromedriver app@1.0.0 ***\app └── chromedriver@94.0.0 npm run e2e が成功する事を確認する $ npm run e2e > app@1.0.0 e2e > node test/e2e/runner.js Starting selenium server... started - PID: 78188 [Login] Test Suite ====================== Running: ログイン { parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }. √ Element <#app> was visible after 113 milliseconds. √ Element <form > .form-actions > button> was visible after 61 milliseconds. √ Element <#app > p> was visible after 583 milliseconds. √ Testing if the URL equals "http://localhost:8080/#/". OK. 4 assertions passed. (16.371s) 以上
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

npmでモジュールと同時にTypeScriptの型情報もインストールする

準備 typesyncをインストールする $ npm i -D typesync package.jsonのscriptsに以下を記述する "scripts": { "postinstall": "typesync" },
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Firebase Authのカスタムクレームをターミナルから簡易に設定する

サービスの管理者でも、全権限がある人や、アルバイトで一時的に入った人など、細かく権限を設定したいものです。 Firebase Authのカスタムクレームという機能を使えば、細かい権限設定が行えます。 しかし、その登録はAdmin SDKを介するので、NodeのRepl環境で行うのは、認証情報の初期化がややこしいです。 個人的にかなりつまづいたので、共有させていただきます。 localのfunctionsディレクトリでNodeを起動 まず、ターミナルでfunctions/のディレクトリに移動してNode Replを起動します。 cd XXX/functions/ node サービスアカウントの秘密鍵を作成 Firebase Consoleのプロジェクトの設定に移動する サービスアカウント のタブを開く 秘密鍵を生成してダウンロードして、保存したパスをコピーしておく サービスアカウントの秘密鍵のパスを環境変数に設定 export GOOGLE_APPLICATION_CREDENTIALS='PRIVATE_KEY_PASS' これにて、自動でAdmin SDKが認証情報を取り扱ってくれます。 公式ドキュメントによると、これ以外の方法である認証情報をハードコードすることは推奨されていません。 Admin SDKが正しく初期化できることを確認する NodeのReplへの入力 const admin = require('firebase-admin'); admin.initializeApp(); カスタムクレームが既に存在するか確認 該当ユーザにカスタムクレームが既に追加されているか確認しましょう。 これは、Admin SDKから行えるカスタムクレームへの操作が、既存のカスタムクレームに対する上書き操作であるからです。 NodeのReplへの入力 const uid = 'XXXXXXXX'; auth.getUser(uid).then((res,rej)=>{console.log(res.customClaims)}); このconsole出力がundefinedなら、該当ユーザに対するカスタムクレームは追加されていないことを示します。 一方で、以下のようなオブジェクトが出力される場合は、カスタムクレームが既に存在するので、値を追加する場合は、既にある存在を保持しつつ値を使いするように注意する必要があります。 console出力 { role: { tempStaff: true } } ですので、これらの既にあるkey,valueのペアを保存し統合された値を上書きするということをお勧めします。 疑似コード let savedCustomClaimObject = { role: { tempStaff: true } }; savedCustomClaimObject.newKey = newValue; admin.auth().setCustomUserClaims(uid, savedCustomClaimObject) トラブルシューティング based on my failures Error: Cannot find module 'firebase-admin' Error: Cannot find module 'firebase-admin' Require stack: - <repl> at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15) at Function.Module._load (internal/modules/cjs/loader.js:687:27) at Module.require (internal/modules/cjs/loader.js:849:19) at require (internal/modules/cjs/helpers.js:74:18) { code: 'MODULE_NOT_FOUND', requireStack: [ '<repl>' ] 解決策: ディレクトリを確認 ローカルのfunctionsのディレクトリに移動してることを確認しましょう。このディレクトリでnode起動する必要があります。 Error: Failed to determine project ID > (node:6503) UnhandledPromiseRejectionWarning: Error: Failed to determine project ID: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND at FirebaseAppError.FirebaseError [as constructor] ... 解決策:秘密鍵の環境変数を再確認しよう これが全てとは限りませんが、再度export GOOGLE_APPLICATION_CREDENTIALS ... の操作を実行しましょう。環境変数は現在のシェルのセッションのみで有効なので、違うターミナルウィンドウ開いた時は、再度環境変数を入れる必要があるので要注意です。 References 公式ドキュメントしか勝たん
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Reactのcreate-react-appの後npm startでエラー

結構しょーもないことに時間食ってしまったので・・・ 全く仕組みを理解していない自分が悪く、調べ方も悪かったので起動するまでの段で時間を食ってしまってテンションが下がったので恥を書き込んでおく反省投稿です・・・。 Windows上でReactの勉強をしようとNode.jsの最新版をインストールし、本を見ながら、 npx create-react-app my-app とかした後、 npm start したらエラーが出て起動できなかったと。 エラーはこんなのです。 :\Users\user\reacttest\my-app>npm start > my-app@0.1.0 start c:\Users\user\reacttest\my-app > 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.44.2" 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: c:\Users\user\node_modules\webpack (version: 4.8.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 c:\Users\user\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! my-app@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the my-app@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! C:\Users\user\AppData\Roaming\npm-cache\_logs\2021-10-25T00_51_59_790Z-debug.log c:\Users\user\reacttest\my-app> 解決前にやったこと ログを見ながらその通りにやった(つもりだったが間違っている) ・pacage-lock.jsonの削除 ・node_modulesフォルダーの削除 ・package.jsonからwebpackを削除、、、しようと思ったけど記述がなかったので放置 ・npm install で、だめで、stack overflowとか調べにいくと同じような感じのことが色々書かれてやってみるものの駄目。 結局・・・ ホームディレクトリ(C:\Users\user)以下にnode_modulesフォルダーが残っていて、ここに大量に古いモジュールがインストールされていた。 ログを見たらきちんとC:\Users\user\node_modulesと書いてある・・・。 それを勝手にcreate-react-appしたフォルダーと勘違いしてそちらを操作していたorz 解決 cd C:\Users\user rd /S /Q node_modules の後、再度 cd C:\Users\user\reacttest\my-app npm start 無事起動しました・・・。なんかこれで2時間くらいハマってました・・・orz やっと一歩目が踏み出せたので引き続きやっていきます・・・。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む