LoginSignup
9
14

More than 5 years have passed since last update.

AndroidスマホでNode.jsをマルチスレッド処理させてみた

Posted at

ポケットの中に夢が拡がる.. .

と言う訳で、今回はTermuxを使って、AndroidにNode.js環境を構築してみます。

導入

1. アプリのインストール

Termux - Google Play
Android向けLinux実行環境。
よくあるターミナルエミュレータアプリより高機能で、感覚的にはUbuntuターミナルに近い。

DroidEdit - Google Play
高機能テキストエディタ。
各言語のシンタックスハイライトやインデントに対応しているので便利。

2. Node.jsのインストール

Termuxを起動して、作業を進めます。

apt update
apt upgrade

aptが使えます。
Temux専用のパッケージリポジトリに繋がっている模様。

apt install coreutils
apt install nodejs

インストールはコレだけ。
Node.js以外にも、各種スクリプト言語エンジンの最新版バイナリが揃っているようです。

3. 動作確認

node -v
npm -v

Stable版がインストールされていると思います。

動かしてみる

Expressを使った簡易Webサーバーを書いてみます。
折角マルチコアSoCなので、clusterモジュールを使ったマルチスレッド処理も試す事にしました。

npm inatall -g express


JavaScript
main.js
const cluster = require("cluster");
const fs = require("fs");

const express = require("/data/data/com.termux/files/usr/lib/node_modules/express");

const cpus = require("os").cpus().length;
const app = express();

const port = 8001;

if(cluster.isMaster){

  console.log("node.js test app");
  console.log("Listen: " + port);

  for(let i = 0; i < cpus; i++){
    cluster.fork();
  }

  cluster.on("fork", (worker)=>{
    console.log("Starting Worker ID: " + worker.id);
  });

  cluster.on("exit", (worker, code, signal)=>{
    console.log("Worker " + worker.id + " is died");
  });
}

else if(cluster.isWorker){

  app.get("/", (req, res)=>{
    console.log("Request from: " + req.connection.remoteAddress);

    res.setHeader("Content-Type", "text/html");
    res.send(fs.readFileSync("./index.html"));

    console.log("Processing Worker ID: " + cluster.worker.id);
  });

  app.listen(port);
}



HTML
index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Node.js on Android!</title>

    <style>
      body {
        margin: 0;
        padding: 0;
        width: 100%;        
      }
    </style>

    <script>
      document.getElementById("bar").click = ()=>{
        const text = document.getElementById("foo").value;
        alert(text);
      }
    </script>
  </head>

  <body>
    <input type="text" id="foo"></input>

    <button id="bar">
      Click Here
    </button>
  </body>
</html>

node main.js

Screenshot_20180618-203334.png

Chromeでlocalhost:8001に接続すると、無事にページが表示されました。
ターミナルではWorkerが6個走ってるのが確認できます。
3回ほどページリロードしましたが、Requestが毎回別のWorkerに割り当てられている事も確認できました。

今回使用したスマートフォンはSM-G930Fで、Exynos8890は8コアですが、恐らくkernelの電力コントロール絡みで、使用可能コアは6個と判断されるようです。

まとめ

動いたからと言って、今すぐ世界が変わる訳では無いですが...
今までPCでしか出来なかった事が、だんだん掌の上で出来るようになっていくの、とてもワクワクしますね。

活用案ゆるぼ、と言う事で締めたいと思います。
それではまた。

9
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
14