CEP で npm モジュールを使う

cep のエクステンションの中で、npm のモジュールを使うこともできます。試しに request モジュールを利用して、openBD の api から書誌データを取得してみます。

テンプレートを作り設定を変える

前回の要領で新しいエクステンションのひな形を作ります。manifest.xml を編集します。 <HostList> の箇所で InDesign を対象に加え、 <Resources> の箇所で node.js を有効化します。

<Host Name="IDSN" Version="[10.0,99.9]" />
<Resources>
<MainPath>./index.html</MainPath>
<ScriptPath>./jsx/hostscript.jsx</ScriptPath>
<CEFCommandLine>
    <Parameter>--enable-nodejs</Parameter>
</CEFCommandLine>
</Resources>

エクステンションフォルダに request モジュールをインストールする

エクステンションを編集している VSCode のウィンドウで、メニューから「ターミナル>新しいターミナル」を開きます。npm コマンドを実行してモジュールをインストールします。init はしなくてもいいのかもしれません。よく知りません。

> npm init
> npm install request

エクステンションのフォルダの中にnode_modulesフォルダが出来て、モジュールがインストールされます。

main.js の記述

get_data 関数を定義します。request モジュールを require で読み込みます。url 文字列を変数に格納します。request に渡すオプションのオブジェクトを定義します。request.getにオプションを渡し、コールバック関数の中で受け取った結果から書籍のタイトルのアラートを出します。ボタンを押したら実行する関数を get_data に変えます。

(function () {
    'use strict';

    var csInterface = new CSInterface();

    var get_data = function () {
        var request = require('request');
        var url = 'https://api.openbd.jp/v1/get?isbn=978-4-86642-009-7'
        var request_options = {
            url: url,
            method: 'GET',
            json: true
        }

        request.get(request_options, function(err, res, body) {
            alert(body[0].summary.title);
        })

    }
    
    
    function init() {
                
        themeManager.init();
                
        $("#btn_test").click(get_data);
    }
        
    init();

}());

index.html の記述

index.html は、一応ボタンのラベルを変えておきます。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
        
<link rel="stylesheet" href="css/topcoat-desktop-dark.min.css"/>
<link  id="hostStyle" rel="stylesheet" href="css/styles.css"/>

<title></title>
</head>

<body class="hostElt">

    <div id="content">        
        
        <div>                
            <button id="btn_test" class="topcoat-button--large hostFontSize">openBDからデータを取得</button>                
        </div>   
        
    </div>
    
    <!-- These are debugging shortcuts.  Class debuglink items only appear in debug mode  -->
    <span class="debuglink" id="reload">Reload</span>
    <span class="debuglink" id="debug">Debug</span>
    <span class="debuglink" id="sources">Sources</span>
    
    <script src="js/libs/CSInterface.js"></script>
    <script src="js/libs/jquery-2.0.2.min.js"></script>

    <script src="js/themeManager.js"></script>
    <script src="js/main.js"></script>

        
</body>
</html>

完成

InDesign でエクステンションを開き、ボタンを押すと書名のアラートが出ます。

このあとは、openBD から書誌データを取得して、InDesign で簡単な書籍目録をつくるようにしていきたいと思います。 何回かに分けてちょっとずつやっていきます。

参考

コメントを残す

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

CAPTCHA