20210428のNode.jsに関する記事は8件です。

ローカル環境でテストに用に起動できるSAML-IdPサーバ

動機 SAML認証の学習、テストのためにローカルで起動するサーバが欲しかったのですが、日本語で解説してあるページが少なく苦労したので、ここに手順を残します。 https://www.npmjs.com/package/saml-idp コマンドラインから起動できるテスト用のIdP(Identity Provider)です。 opensslをで証明書を作成するので、gitbashで操作するなどしてください。 ※SAML認証サンプルプログラムを作成しました。 https://qiita.com/murasuke/items/9bf5ca8083d1da3dd66f テスト用IdP(saml-idp)のインストールと設定 npmでインストールを行うため、とりあえずpackage.jsonを作成します。 npm init -y saml-idpをインストール(package.jsonへ追加)します。 npm i -D saml-idp IdP用証明書ファイル作成(IdPの必須ファイル) 作成したファイルをプロジェクトルートに配置します。(ルートディレクトリでコマンドを実行すれば、コピーする必要はありません) openssl req -x509 -new -newkey rsa:2048 -nodes -keyout idp-private-key.pem -out idp-public-cert.pem -days 7300 Generating a RSA private key Country Name(国名), State or Province Name(県名), Locality Name(都市名)などは、テスト用途なので適当に入力してください。 出力するファイル名(idp-public-cert.pem)は、saml-idpのデフォルト名を指定しています。変更する場合は、起動時のコマンドライン指定を修正する必要があります。 作成コマンドサンプル $ openssl req -x509 -new -newkey rsa:2048 -nodes -keyout idp-private-key.pem -out idp-public-cert.pem -days 7300 Generating a RSA private key .....+++++ ......+++++ writing new private key to 'idp-private-key.pem' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:JP State or Province Name (full name) [Some-State]:Aichi Locality Name (eg, city) []:Nagoya Organization Name (eg, company) [Internet Widgits Pty Ltd]: Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:Test Identity Provider Email Address []:test@example.com 起動用スクリプト登録 package.jsonの"scripts"に、テスト用IdP起動スクリプトを追加します。 "saml-idp": "saml-idp --acs http://localhost:7000/auth/saml --aud mock-audience" 動作確認 テスト用Idpサーバ(saml-idp)を起動します。port:7000番でListenします $ npm run saml-idp > simple-saml-auth@0.0.0 saml-idp C:\Users\test\Documents\git\auth\simple-saml-auth > saml-idp --acs http://localhost:7000/auth/saml --aud mock-audience Listener Port: localhost:7000 HTTPS Enabled: false [Identity Provider] Issuer URI: urn:example:idp Sign Response Message: true Encrypt Assertion: false Authentication Context Class Reference: urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport Authentication Context Declaration: None Default RelayState: None [Service Provider] Issuer URI: None Audience URI: mock-audience ACS URL: http://localhost:7000/auth/saml SLO URL: None Trust ACS URL in Request: true Starting IdP server on port localhost:7000... IdP Metadata URL: http://localhost:7000/metadata SSO Bindings: urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST => http://localhost:7000/saml/sso urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect => http://localhost:7000/saml/sso IdP server ready at http://localhost:7000 ブラウザでアクセスして下記のような画面が出ればOKです。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Windows 版 Node.js 手動セットアップ手順

管理者権限が無い Windows 10 (64-bit) で Node.js を使うための手順です。 Web ブラウザーを開き, Download | Node.js にアクセスする。 Windows Binary (.zip) の 64-bit をクリックし, アーカイブをダウンロードする。 ダウンロードしたアーカイブを展開し, C ドライブの直下に移動する。 今回は C:\node-v14.16.1-win-x64 というフォルダーに, node.exe や npm.cmd が存在するものとする。 Windows 10 環境変数設定手順 を参考に, 環境変数 Path に C:\node-v14.16.1-win-x64 を追加する。 スタートメニューを右クリックし, コマンド プロンプト をクリックする。 コマンドプロンプトが開く。 node --version や npm --version と実行し, バージョン情報が表示されることを確認する。 > node --version v14.16.1 > npm --version 6.14.12 どっとはらい。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

DynamoDBクライアントでインスタンスが同じならセッション再利用されるのか実験してみた

AWS SDK for JavaScriptを使ってDynamoDBを利用する場合、AWS.DynamoDBインスタンスを生成し、これを通してAPIアクセスを行うことになりますが、その際のセッションがどうなっているのか気になって調べてみました。 お急ぎの方に結論 オプションもしくは環境変数を設定すればセッションは再利用されます。 参考 準備 DynamoDB localを起動し、これにアクセスするコードを用意します。 (DynamoDB localがポート18005で動いています) TCPセッションの状態はlsof -i@localhostで確認します。 実験1 以下のようなコードを用意しました。 DynamoDBインスタンスは1つ作成し、APIを2回実行します。 import { DynamoDB } from 'aws-sdk'; import { execSync } from 'child_process'; process.env.AWS_REGION = 'ap-northeast-1'; function getDynamoDB() { return new DynamoDB({ endpoint: 'http://localhost:18005', }); } function printSession() { try { const stdout = execSync('lsof -i@localhost | grep node'); console.log(stdout.toString()); } catch (e) { console.error('null'); } } async function main() { console.log('#0'); printSession(); const cl = getDynamoDB(); console.log('#1'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#2'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#3'); printSession(); } main(); 以下が出力されました。 #0 null #1 null #2 node 98657 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56434->localhost:18005 (CLOSE_WAIT) #3 node 98657 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56435->localhost:18005 (CLOSE_WAIT) インスタンス作っても接続はされないんですね。 クライアント側のポートが異なるものが・・・ということは、それぞれでセッションが作られていそうです。 実験2 公式がズバリな記事を用意していました。 Reusing Connections with Keep-Alive in Node.js keepAliveを設定してみます。 import { DynamoDB } from 'aws-sdk'; import { execSync } from 'child_process'; import * as http from 'http'; process.env.AWS_REGION = 'ap-northeast-1'; function getDynamoDB() { return new DynamoDB({ endpoint: 'http://localhost:18005', httpOptions: { agent: new http.Agent({ keepAlive: true, }), }, }); } function printSession() { try { const stdout = execSync('lsof -i@localhost | grep node'); console.log(stdout.toString()); } catch (e) { console.error('null'); } } async function main() { console.log('#0'); printSession(); const cl = getDynamoDB(); console.log('#1'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#2'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#3'); printSession(); } main(); 実行すると以下が出力されました。 #0 null #1 null #2 node 99003 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56503->localhost:18005 (ESTABLISHED) #3 node 99003 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56503->localhost:18005 (ESTABLISHED) ちゃんと再利用されていそうです。 実験3 ちなみに、別インスタンスを作ると?と思って念のための追試です。 import { DynamoDB } from 'aws-sdk'; import { execSync } from 'child_process'; import * as http from 'http'; process.env.AWS_REGION = 'ap-northeast-1'; function getDynamoDB() { return new DynamoDB({ endpoint: 'http://localhost:18005', httpOptions: { agent: new http.Agent({ keepAlive: true, }), }, }); } function printSession() { try { const stdout = execSync('lsof -i@localhost | grep node'); console.log(stdout.toString()); } catch (e) { console.error('null'); } } async function main() { console.log('#0'); printSession(); const cl = getDynamoDB(); console.log('#1'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#2'); printSession(); await cl.describeTable({ TableName: 'test-table' }).promise(); console.log('#3'); printSession(); const cl2 = getDynamoDB(); console.log('#4'); printSession(); await cl2.describeTable({ TableName: 'test-table' }).promise(); console.log('#5'); printSession(); } main(); 以下が出力されました。 #0 null #1 null #2 node 99143 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56510->localhost:18005 (ESTABLISHED) #3 node 99143 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56510->localhost:18005 (ESTABLISHED) #4 node 99143 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56510->localhost:18005 (ESTABLISHED) #5 node 99143 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56510->localhost:18005 (ESTABLISHED) node 99143 user 35u IPv4 0x108da27b1d53185d 0t0 TCP localhost:56511->localhost:18005 (ESTABLISHED) インスタンスまたいで共有はされませんね。 結果 短い時間に複数回の操作を呼び出すユースケースがある場合は、keepAlive設定するか、公式に記載のAWS_NODEJS_CONNECTION_REUSE_ENABLEDを利用するのがよさそうです。 AWS_NODEJS_CONNECTION_REUSE_ENABLEDを設定すると別インスタンスでもセッションが共有されます。 keepAliveを使う場合、この実験ではローカル接続でhttpでしたが、AWS環境で有効にするにはhttps.Agentにする必要があります。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

electronでpython ファイルを使用する際の覚書

概要 electronはHTML, CSS, Javascriptを使って簡単にWindows, mac, linux のマルチプラットフォームにアプリを作成できるフレームワークです。 今回electronとpythonコードを連携させる際のファイル構造に関しての覚書です。 electronにおけるFrontend,Backend間の情報のやり取りの変遷 https://qiita.com/pochman/items/64b34e9827866664d436 こちらの記事に詳しく書かれていますが、electronはこれまでversionが上がるたびにSecurityの観点からipc通信の仕様を変更しています。これから先も変更になる可能性はありますが、2021年4月の時点の情報です。 全体の構成図 main.js設定 const electron = require('electron'); const app = electron.app; const path = require("path"); const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; const ipcRenderer = electron.ipcRenderer; //ここでpyhonshell library を呼び出す const {PythonShell} = require("python-shell"); let mainWindow; function createWindow() { // メインウィンドウを作成します mainWindow = new BrowserWindow({ width:1100, height: 1000, webPreferences: { nodeIntegration: false, contextIsolation: true, preload: path.join(__dirname, 'preload.js') }, }); // メインウィンドウに表示するURLを指定します // (今回はmain.jsと同じディレクトリのindex.html) mainWindow.loadFile('index.html'); // デベロッパーツールの起動 mainWindow.webContents.openDevTools(); // メインウィンドウが閉じられたときの処理 mainWindow.on('closed', () => { mainWindow = null; }); } // 初期化が完了した時の処理 app.on('ready', createWindow); // 全てのウィンドウが閉じたときの処理 app.on('window-all-closed', () => { // macOSのとき以外はアプリケーションを終了させます if (process.platform !== 'darwin') { app.quit(); } }); // アプリケーションがアクティブになった時の処理(Macだと、Dockがクリックされた時) app.on('activate', () => { // メインウィンドウが消えている場合は再度メインウィンドウを作成する if (mainWindow === null) { createWindow(); } }); //ここでpreload.jsからのipc通信を受け取り、python-shellを起動 //pythonで書かれたコードを呼び出す ipcMain.handle('hoge',async (event, data) => {  //pythonに渡す何らかのパラメーター var options = { data:data } //ここでパラメーターと共に渡す let pyshell =await new PythonShell('hogehoge.py', options);  //pythonでのコード処理が終わったらpythonからexportされたメッセージを受け取る //preload.jsにpythonから吐き出されたデータを送る pyshell.on('message', async function(message) { event.sender.send("return_data", message) }) }) preload.js const { contextBridge, ipcRenderer} = require("electron") //main.jsに書かれた"hoge" handlerを起動している contextBridge.exposeInMainWorld('api', { send: async (data) => await ipcRenderer.invoke('hoge', data), on: (channel, func) => { ipcRenderer.on(channel, (event, data) => func(data)); } } ); index.html <script> //ここでpreload.jsで作成されたapiを呼び出して何らかのデータを渡す const message= window.api.send({"send_data":send_data}) const message2=window.api.on("return_data", async (data)=>{ //returnされたデータを使った処理をこちらに書く }) </script> 最後に electronを使用してpythonコードをつかったアプリを作る必要があったため、自分用としてまとめておきました。非常にざっくりとした記事ですが、どなたかのお役に立てれば幸いです。 もし不備などありましたらお知らせいただけると幸いです。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

QRコードリーダーLINEBotを作る【nodejs】

完成デモ 抱えてた課題 nodejsでQRコードを解析する場合、fsモジュールでプロジェクト配下に画像をダウンロードする必要がある。 AWS Lambdaでそれをやろうとすると、read onlyなのでダウンロードはできないと言われて困った。 S3なんかに画像をアップロードする手もあったかもしれないが、そこまでのことでもなかったので、解決策を探した。 ▼Lambdaで怒られてる画像 ▼参考にしたサイト Node.jsでQRコードを読み込む 解決策 LINEから送られてきた画像を取得し、jimpとqrcode-readerのモジュールを利用する index.js //Lambdaで動かす "use strict"; // モジュール呼び出し const crypto = require("crypto"); const line = require("@line/bot-sdk"); const QRReader = require("qrcode-reader"); const jimp = require("jimp"); // インスタンス生成 const client = new line.Client({ channelAccessToken: process.env.ACCESSTOKEN }); exports.handler = (event) => { let signature = crypto .createHmac("sha256", process.env.CHANNELSECRET) .update(event.body) .digest("base64"); let checkHeader = (event.headers || {})["X-Line-Signature"]; if (!checkHeader) { checkHeader = (event.headers || {})["x-line-signature"]; } const body = JSON.parse(event.body); const events = body.events; console.log(events); // 署名検証が成功した場合 if (signature === checkHeader) { events.forEach(async (event) => { let message; switch (event.type) { case "message": message = await messageFunc(event); break; case "postback": message = await postbackFunc(event); break; case "follow": message = { type: "text", text: "追加ありがとうございます!" }; break; } // メッセージを返信 if (message != undefined) { await sendFunc(body.events[0].replyToken, message); // .then(console.log) // .catch(console.log); return; } }); } // 署名検証に失敗した場合 else { console.log("署名認証エラー"); } }; async function sendFunc(replyToken, mes) { const result = new Promise(function (resolve, reject) { client.replyMessage(replyToken, mes).then((response) => { resolve("送信完了"); }); }); return result; } async function messageFunc(event) { let message = ""; message = { type: "text", text: `メッセージイベント` }; if (event.message.type === "image") { const imageBuffer = await (() => new Promise((resolve) => { client.getMessageContent(event.message.id).then((stream) => { const bufs = []; stream.on("data", (chunk) => { bufs.push(chunk); }); stream.on("end", async () => { resolve(Buffer.concat(bufs)); }); stream.on("error", (err) => { // error handling }); }); }))(); const img = await jimp.read(imageBuffer); const qr = new QRReader(); const value = await new Promise((resolve, reject) => { qr.callback = (err, v) => (err != null ? reject(err) : resolve(v)); qr.decode(img.bitmap); }); message = { type: "text", text: `解析結果${value.result}` }; } return message; } const postbackFunc = async function (event) { let message = ""; message = { type: "text", text: "ポストバックイベント" }; return message; }; リポジトリ lambda版も作った おわりに ずっと悩んでたことが解決できてよかった!! ここもよかったら参考にどうぞ
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

簡単にRESTサーバ・GraphQLサーバを立ち上げる

前回の投稿 JavascriptのImportとVueのコンポーネントを使えるようになってみる に引き続き、テンプレート環境の使い方をまとめておきます。 今回はサーバ側ということで、RESTサーバとGraphQLサーバの立ち上げ方を備忘録としてまとめておきます。 テンプレートは以下のGitHubに上げてあります。 poruruba/express_template https://github.com/poruruba/express_template ※たびたび機能追加しているので、ここに記載していない機能も入っている可能性大です。 RESTサーバを立ち上げる api/controllers/の配下に、適当なフォルダを作成し、index.jsとswagger.yamlを作成します。 index.jsは通常は、API Gateway経由でLambdaに転送されたときに似せています。 (i) JSON/POST呼び出しの場合 受け付けた呼び出しは、index.jsのexports.handlerで受け取ることができます。BODYに指定された引数を取得するには、以下のようにします。 exports.handler = async (event, context, callback) => { var body = JSON.parse(event.body); (ii) GET呼び出しの場合 同様に、受け付けた呼び出しは、index.jsのexports.handlerで受け取ることができます。QueryStringの引数を取得するには、以下のようにします。 exports.handler = async (event, context, callback) => { var params = event.queryStringParameters; レスポンスは、application/jsonで返すことが多いので、ヘルパー関数を用意しています。 こんな感じで返します。 return new Response({ message: 'Hello World' }); もし、バイナリで返す場合は以下のようにします。 return new BinResponse("application/octet-stream", buffer); もし、テキストで返す場合は以下のようにします。 return new TextResponse("text/html", str); リダイレクトさせたい場合には、以下のようにします。 return new Redirect(url); swagger.yamlには、エンドポイントを定義します。Swagger2.0の定義のうちの、pathsとdefinitionsを定義します。(ただし、実際に参照しているのは、エンドポイント名だけですが。。。) api/controllers/フォルダ配下にサンプルを置いていますので参考にしてください。 いくつかオプション設定できるようにしました。 〇オプションタグ: x-hanndler  x-hanndler: 任意 通常は、エンドポイントが呼ばれると、index.jsのexports.handlerが呼び出されますが、このhandlerじゃない関数名で呼ばれたい場合にはここで指定します。 認証の検証をするわけではないのですが、パースして、index.js に結果を渡してあげます。 〇オプションタグ: security security: - basicAuth: [] - tokenAuth: [] - apikeyAuth: [] - jwtAuth: [] basicAuth : クライアントIDとクライアントシークレットがBase64でエンコードされた認証情報です。  Authorization: basic [Bases64Encode(‘client_id’:’client_secret’)] tokenAuth:OpenID ConnectやOAuth2のトークンを指定する場合の認証情報です。  Authorization: bearer [Token] apikeyAuth:APIキーを使った認証情報です。  X-API-KEY:[APIKey] jwtAuth:GCPのCloud Endpoint認証のための認証情報です。  Authorization: bearer [Token] Authorizationヘッダが設定されて呼び出される場合に指定します。req.requestContext に解析結果が設定されます。 〇オプションタグ: x-functype x-functype: (express|empty|normal|alexa|lambda) index.jsの呼び出し型を指定します。通常はnormalで、API Gateway経由でlambdaが呼ばれたときと同じようにふるまいますが、型を変えたい場合に指定します。 一応、忘れないように。Multipartでファイルを送るときは以下の指定にします。 〇file(multipart/form-data)の処理 parameters: - in: formData type: file name: 任意 event.files.upfile[0] に受信したバイナリが格納されます。 npm run startで起動させると、api/controllers/配下の各フォルダにあるswagger.yamlを検索し、自動的にエンドポイントの定義を読み出して、エンドポイントを立ち上げるようにしています。 また、https://localhost:10080/swagger にアクセスすると、Yaml形式のSwagger定義をテキストで取得できます。 なので、以下のようなSwaggerエディタから、エンドポイントを可視化したり試しに呼び出しができます。 Swagger-Editor  https://editor.swagger.io/ swagger-api/swagger-editor  https://github.com/swagger-api/swagger-editor File ⇒ Import URL で表示されるダイアログボックスに、立ち上げた上記のURLを入力してみてください。 npm run swaggerを実行することでも、各フォルダのswagger.yamlを結合してapi/swagger/swagger.yaml というファイルを出力することもできます。 GraphQLサーバの立ち上げ api/controllers/の配下に、適当なフォルダを作成し、index.jsとschema.graphqlを作成します。 index.jsは以下のような感じで引数を取得し、schema.graphqlで定義したレスポンスに従って返すように実装します。 以下例です。 exports.handler = async(parent, args, context, info) =>{ console.log("args", JSON.stringify(args)); console.log("path", info.path); return "Hello World"; }; schema.graphqlは、もちろんGraphQLです。 ※Subscriptionはまだ実装していませんので、書いても動きません。。。 例えばこんな感じです。 type Query { hello(message: String, param: Int): String } アノテーションでオプションを定義できるようにしています。 @endpointアノテーション schema @endpoint(endpoint: "/mygraphql"){ query: Query, } 上記のアノテーションを記載しておくと、指定されたエンドポイント名でGraphQLのエンドポイントを立ち上げます。 上記の例では、エンドポイントは以下のようになります。  http://localhost:10080/mygraphql 上記のアノテーションがない場合には、エンドポイントは自動的に以下のように割り当たります。  http://localhost:10080/【フォルダ名】 @handlerアノテーション type Query @handler(handler: "fulfillment", type: "lambda"){ hello(param1: String, param2: Int): MyModelType test: [ToDo] } 通常は、index.jsの呼び出しは、express_graphqlの呼び出し形式ですが、type:lambdaとすると、AWSのAppSyncに似せることができます。 handlerの定義は、通常は、index.js のexports.handerが呼び出されますが、名前を変えたい場合に指定します。handler: fulfillmentとした場合には、以下の部分が呼び出されます。 exports.fulfillment = async(parent, args, context, info) =>{ また、GraphQLエクスプローラも立ち上がるようにしています。 http://localhost:10080/graphql をブラウザで開くと以下のようなページが表示されます。 自動で立ち上げたGraphQLのフォルダ名が表示されています。 いずれかを選択すると、以下のようなGraphQLエクスプローラが立ち上がり、GraphQLのQueryやMutationの定義を確認したり、実際に実行を試すことができます。 ヘルパー Alexaスキル、Alexaスマートホーム、Clova、LINEボット、Slack、Dialogflowなどとつなぐのに便利なヘルパをapi/helpers/に用意しています。 今後加筆するかもしれませんが、とりあえず以下を参考にしてください。ベースがテンプレート環境ではなくSwagger-Node環境で異なるのですが、ヘルパの使い方は同じです。  SwaggerでLambdaのデバッグ環境を作る(1) 終わりに こちらもご参考にどうぞ  JavascriptのImportとVueのコンポーネントを使えるようになってみる 以上
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【M1 Mac】nodebrew v1.1.0で公式にAppleSiliconに対応したのでNode v16.0.0をインストール

はじめに M1 Mac nodebrewが公式にAppleSiliconに対応したらしい(2021-04-23) https://github.com/hokaccha/nodebrew/blob/master/History.md#110---2021-04-23 遭遇したエラー 以下のコマンドで簡単にNodeがインストールできるということで、実行してみたところ $ nodebrew install v16.0.0 なんかたくさんエラーでてる〜〜!!! 対応したちゃうんか〜!!!? Fetching: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz Warning: Failed to create the file Warning: /Users/merarli/.nodebrew/src/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz: Warning: No such file or directory curl: (23) Failed writing body (0 != 978) download failed: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz 理由はわかりませんが、Homebrew経由でnodebrewをインストールしたのが原因っぽい nodebrew インストール Homebrew経由でインストールのが悪いのかと思って、homebrewでインストールしたnodebrewをアンインストール後、 $ brew rm nodebrew 公式のGitHubに書いてあるcurlインストールのやり方でインストール https://github.com/hokaccha/nodebrew 初めてインストールする人はここから始めてください $ curl -L git.io/nodebrew | perl - setup インストール完了後 以下のパスを~/.zshrcの下部に記述してください export PATH=$HOME/.nodebrew/current/bin:$PATH 以下のコマンドで変更した~/.zshrcを再読み込みします。 ※ターミナル再起動でもOKです! $ source ~/.bashrc 以下のコマンドでバージョンを確かめると $ nodebrew -v 最新のv1.1.0になっていることがわかります。 $ nodebrew -v nodebrew 1.1.0 Usage: nodebrew help Show this message nodebrew install <version> Download and install <version> (from binary) nodebrew compile <version> Download and install <version> (from source) nodebrew install-binary <version> Alias of `install` (For backward compatibility) nodebrew uninstall <version> Uninstall <version> nodebrew use <version> Use <version> nodebrew list List installed versions nodebrew ls Alias for `list` nodebrew ls-remote List remote versions nodebrew ls-all List remote and installed versions nodebrew alias <key> <value> Set alias nodebrew unalias <key> Remove alias nodebrew clean <version> | all Remove source file nodebrew selfupdate Update nodebrew nodebrew migrate-package <version> Install global NPM packages contained in <version> to current version nodebrew exec <version> -- <command> Execute <command> using specified <version> node v16.0.0 インストール nodebrewのインストールが終わったので、node v16.0.0をインストール $ nodebrew install v16.0.0 こんな感じにログがでてインストールが完了します。 Fetching: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz ####################################################################################################################### 100.0% Installed successfully 以下のコマンドでインストールされたNodeのバージョンを確かめると $ nodebrew ls 以下のようにでるので、 use v16.0.0 v16.0.0を使用する以下のコマンドを入力 $ nodebrew use v16.0.0 最後にNodeのバージョンを以下のコマンドで確認 $ node -v 以下のようにでれば成功です! v16.0.0
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【M1 Mac】nodebrew v1.1.0が公式にAppleSiliconに対応したのでNode v16.0.0をインストール

はじめに M1 Mac nodebrewが公式にAppleSiliconに対応したらしい(2021-04-23) https://github.com/hokaccha/nodebrew/blob/master/History.md#110---2021-04-23 遭遇したエラー 以下のコマンドで簡単にNodeがインストールできるということで、実行してみたところ $ nodebrew install v16.0.0 なんかたくさんエラーでてる〜〜!!! 対応したちゃうんか〜!!!? Fetching: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz Warning: Failed to create the file Warning: /Users/merarli/.nodebrew/src/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz: Warning: No such file or directory curl: (23) Failed writing body (0 != 978) download failed: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz 理由はわかりませんが、Homebrew経由でnodebrewをインストールしたのが原因っぽい nodebrew インストール Homebrew経由でインストールのが悪いのかと思って、homebrewでインストールしたnodebrewをアンインストール後、 $ brew rm nodebrew 公式のGitHubに書いてあるcurlインストールのやり方でインストール https://github.com/hokaccha/nodebrew 初めてインストールする人はここから始めてください $ curl -L git.io/nodebrew | perl - setup インストール完了後 以下のパスを~./zshrcの下部に記述してください export PATH=$HOME/.nodebrew/current/bin:$PATH 以下のコマンドで変更した~/.zshrcを再読み込みします。 ※ターミナル再起動でもOKです! $ source ~./zshrc 以下のコマンドでバージョンを確かめると $ nodebrew -v 最新のv1.1.0になっていることがわかります。 $ nodebrew -v nodebrew 1.1.0 Usage: nodebrew help Show this message nodebrew install <version> Download and install <version> (from binary) nodebrew compile <version> Download and install <version> (from source) nodebrew install-binary <version> Alias of `install` (For backward compatibility) nodebrew uninstall <version> Uninstall <version> nodebrew use <version> Use <version> nodebrew list List installed versions nodebrew ls Alias for `list` nodebrew ls-remote List remote versions nodebrew ls-all List remote and installed versions nodebrew alias <key> <value> Set alias nodebrew unalias <key> Remove alias nodebrew clean <version> | all Remove source file nodebrew selfupdate Update nodebrew nodebrew migrate-package <version> Install global NPM packages contained in <version> to current version nodebrew exec <version> -- <command> Execute <command> using specified <version> node v16.0.0 インストール nodebrewのインストールが終わったので、node v16.0.0をインストール $ nodebrew install v16.0.0 こんな感じにログがでてインストールが完了します。 Fetching: https://nodejs.org/dist/v16.0.0/node-v16.0.0-darwin-arm64.tar.gz ####################################################################################################################### 100.0% Installed successfully 以下のコマンドでインストールされたNodeのバージョンを確かめると $ nodebrew ls 以下のようにでるので、 use v16.0.0 v16.0.0を使用する以下のコマンドを入力 $ nodebrew use v16.0.0 最後にNodeのバージョンを以下のコマンドで確認 $ node -v 以下のようにでれば成功です! v16.0.0
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む