Node.jsでQRコードを生成する

node-qrcodeを使用すると、Node.js上で簡単にQRコードを生成できます!

インストール

npm install qrcode

QRコードを画像ファイルで保存する

toFile()を使うと、QRコードの画像ファイルを作成できます。

下記では、test qr code sample.という文字列の入ったQRコードをpublic/images/my-qrcode.pngに保存します。
※あらかじめカレントフォルダにpublic/imagesフォルダを作成しておく必要があります。

index.js
"use strict";

const path = require('path');
const QRCode = require('qrcode');

const imgDir = path.join(path.join(__dirname, 'public'), 'images');

QRCode.toFile(path.join(imgDir, 'my-qrcode.png'), 'test qr code sample.', (error) => {
  if (error) {
    console.log(error);
    return;
  }

  console.log('create qrcode finish.');
});

出力されたQRコード

QRコードのData URIを取得する

toDataURL()を使うと、QRコードのData URIを取得できます。

上記index.jstoFile()の箇所を次のように変更します。

QRCode.toDataURL('test qr code sample.', (error, url) => {
  if (error) {
    console.log(error);
    return;
  }
  console.log(url);
});

urlimgタグsrcに設定するとQRコードがWebページに表示されます。

このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です