Как запустить node js на андроид

Building a Node.js application on Android

by Aurélien Giraud

Building a Node.js application on Android — Part 1: Termux, Vim and Node.js

If you are excited about Node.js and own an Android device, no doubt you’ll enjoy running Node.js on it. Thanks to Termux a terminal emulator and Linux environment for Android, the fun of developping Node.js web applications is just a few ‘npm install’s away!

What we are going to do

I will show how to get started with Node.js using Termux on Android. We are also going to use Express and see how to store our app’s data in NeDB, a lightweight JavaScript database, whose API is a subset of MongoDB’s.

In this first post, we will limit ourselves to setting up our Node.js development environment, that is:

  1. Install and configure Termux.
  2. Install and see how to use Vim as a text editor. (This section can be skipped if you already know Vim.)
  3. Install and run Node.js.

1. Termux

Termux combines terminal emulation with a Linux package collection. It comes as a free app that can be installed directly from the Play Store or from F-Droid catalogue.


When you open Termux, you are greeted by a Command Line Interface (CLI). Right after installing Termux, it is recommended to check for updates, and upgrade if need be. So type the following commands at the prompt — that is, after the ‘$’ sign — and press :

Termux comes with a minimal base system, so you should also install ‘coreutils’ for the full-fledged variants of base CLI utilities such as ‘mv’, ‘ls’, etc.


There are three main types of storage in Termux:

  1. App-private storage: This is right where you are when you start Termux.
  2. Shared internal storage: Storage in the device available to all apps.
  3. External storage: Storage on external SD cards.

Although the environment setup in Termux is similar to that of a modern Linux distribution, running on Android implies differences and so far I have only managed to run Node.js fully while storing my data in Termux’s private storage (option 1 above).

So let’s create a directory for our app and change to this directory:


I have only been using a soft keyboard so far and I encountered some issues with the default touch keyboard while using the volume up key as a replacement for , or the Arrow keys.

To circumvent these issues, I installed Hacker’s Keyboard from the Play Store and I really like it. It is a touch keyboard that can be used instead of the default one and has all the keys needed for writing code and using the terminal.

You can find useful information about using a touch or hardware keyboard with Termux directly on the Help page.

The Hacker’s keyboard

Using multiple sessions

One more thing I would like to mention about Termux: if you swipe the screen left to right from its left edge, it opens a menu that enables to start or switch between multiple Termux sessions.

Accessing Help in Termux

In Termux, you can access the help documentation, which contains all the necessary information, by long pressing the screen, and clicking first on ‘More’, then on ‘Help’. Note though, that this help documentation cannot be accessed when your device isn’t connected to the internet.

2. Vim

Vim is a text editor that can be used right in the Command Line Interface and it is available as a package in Termux. So let’s install it:

Vim’s interface is not based on menus or icons but on commands given in a text user interface. In case you are new to it I’m going to guide you through the very basics of Vim.

First, create the file ‘server.js’:

To edit this file with Vim, simply type:

Vim displaying the content of the empty file server.js

Using the different modes

Vim behaves differently, depending on which mode you are in. At start, you are in what is called command mode. You should see a cursor on the first line, tildes (

) on the other lines and the name of the file at the very bottom.

Tilde lines are here to indicate that these lines are not part of the content of the file.

To start writing into the file, you need to switch to writing mode. So just type the letter “i”. At the very bottom, you should now see something like this:

Vim is now in writing mode

So now go on. Write something.

Done? So here is how you can save your changes/quit Vim. First you need to come back to the command mode by pressing and then you have the choice:

  1. Type :w and press to save (write) the changes.
  2. Type :wq and press to save the changes and quit.
  3. Type :q! and press to quit without saving the changes.

And that is about it for our very short introduction to Vim.

Not getting lost and learning more about Vim

If you are lost, you can press and type :help followed by . This will open Vim help documentation.

Something like this simple Vim Reference might be useful if you are new to Vim. Alternatively, you can type ‘vimtutor’ in the terminal for a 30 minutes tutorial, play a learning game at http://vim-adventures.com/ or follow the interactive tutorial at http://www.openvim.com/.

3. Node.js

Installing Node.js is very simple:

If you haven’t done it yet, create a folder for the application, move into it and type:

This will ask you a bunch of questions, and then write a ‘package.json’ file for you. (You can just press for each question asked.)

Now let us check that everything is working all right. Open server.js

Save the changes and quit Vim.

Now we have everything in place and we can finally run node:

This should print the text “This is Node.js running on Android.” in the terminal.

In a nutshell

As a recap, here is the whole process again (with minor differences as it is all done directly from the command line).

Wrapping it up

We have seen how to use Termux on Android, how to edit files with Vim and how to run Node.js.

Here are a the main links related to Termux: its web page, its wiki and its GitHub repositories. It can be installed from the Play Store or from the F-Droid catalogue.

In the next post we are going to build a basic Node.js application using the Express web framework and a lightweight JavaScript database called NeDB which uses MongoDB’s API and can be used to develop and run a web application in Termux.

In the meantime, happy coding!

If this article was helpful, tweet it .

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.


Запуск NodeJS-приложения на Android

Без сомнения, вам понравится запускать NodeJS на своем Android-устройстве. Благодаря эмулятору терминала и Linux-окружения для Android, разработка веб-приложений на смартфоне перестанет быть для вас проблемой.


Termux — это бесплатное приложение, которое можно установить прямо из магазина Google Play. Требуется версия Android 5.0 или более поздняя. Не требует root-прав.
При открытии Termux вас приветствует интерфейс командной строки. Рекомендуется проверить наличие обновлений сразу после установки Termux. Введите следующую команду и нажмите Enter:

Termux поставляется в минимальной базовой комплектации, так что вы должны установить coreutils для полноценного использования команд командной строки, таких как mv, ls и др.

Termux хранит данные в собственном хранилище данных, т.е. папка $HOME находится внутри частной области Termux, как у обычного Android приложения. Удаление Termux вызовет потерю этих данных. Если вы собираетесь хранить там важные файлы, то используйте termux-setup-storage, чтобы обеспечить сохранение данных во внешнем хранилище (например на SD-карте).

Итак, давайте создадим папку для нашего приложения и перейдем в этот каталог:


В этот момент вы, скорее всего, почувствуете некоторые проблемы при работе в консоли со стандартной клавиатурой. Чтобы обойти их, я установил хакерскую клавиатуру из Google play. Это сенсорная клавиатура, которая имеет все необходимое для написания кода — Esc, Tab и клавиши со стрелками.

Для написания кода нам понадобится любой текстовый редактор, доступный в консоли. Вы можете установить Emacs или Vim, но для простоты можно использовать nano. Установим его:

Создадим файл app.js и откроем его в редакторе:

Напишем какой-нибудь простой NodeJS-код для проверки:

Чтобы выйти из nano, нужно нажать Ctrl+X, написать ‘yes’ и нажать Enter.


Теперь самое время установить NodeJS. Сделать это очень просто:

Теперь мы можем наконец запустить наш скрипт:


Вместе с NodeJS нам доступен пакетный менеджер npm. Давайте воспользуемся им:

Откроем app.js и напишем/скопи-пастим туда следующий код:

Это должно вывести в консоль номер порта по которому отвечает сервер. Если вы откроете http://localhost:8080/ в браузере, то увидите на странице следующий текст:


Чтобы избежать перезагрузки сервера вручную каждый раз при изменении файла app.js мы можем установить nodemon. Nodemon — это утилита, которая будет отслеживать изменения в вашем коде и автоматически перезапустить сервер.

Теперь вы можете запустить сервер с помощью команды nodemon вместо node:

Даже с хакерской клавиатурой писать код на сенсорном экране не очень удобно. Скорее всего, вы пишите свой код в гораздо более удобных местах и храните его в репозитории. Установим git:

Теперь вы можете запускать git команды вроде git push, git pull и т.д. без каких-либо ошибок.


К сожалению, у меня не получилось запустить MongoDB-сервер на Android. В качестве альтернативы можно использовать облачные сервисы, типа MongoLab или довольствоваться чем-то вроде NeDB.


Getting Started: Android native apps¶

Download the library¶

The Android shared libraries are distributed in a zip file, which you can download from the core library release page.

The zip file contains Android binaries for the armabi-v7a , x86 , arm64-v8a and x86_64 architectures.

Creating your First Project¶

The following steps will guide you through creating an Android Studio project that uses the library and is built with Gradle. The complete project can also be downloaded from the samples repo.

This sample runs the Node.js engine in a background thread to start an HTTP server on port 3000 and return the process.versions value. The app’s Main Activity UI has a button to query the server and show the server’s response. Alternatively, it’s also possible to access the server from a browser running on a different device connected to the same local network.

Android SDK Requirements¶

When you build your project, Gradle will automatically try to detect any missing dependencies and prompt you to install them from within the Android Studio event log. Here’s the list of pre-requisites in case you want to download them from the SDK Manager:

  • API Level greater or equal to Marshmallow (API Level 23)
  • CMake
  • Android SDK Platform-Tools greater or equal to Marshmallow (API Level 23)
  • Android SDK Build-Tools greater or equal to Marshmallow (API Level 23)
  • NDK version 15 or greater

Create an Android Studio Project¶

Using the Android Studio’s New Project wizard, create a new Project with the following settings, by the order the options appear in screens:

  1. Include C++ support checked
  2. Phone and Tablet with Minimum SDK to API 21: Android 5.0 (Lollipop)
  3. Empty activity selected
  4. Left the defaults, which were:
    • Activity Name: MainActivity
    • Generate Layout File checked
    • Layout Name: activity_main
    • Backwards Compatibility (AppCompat) checked
  5. Left the defaults, which were:
    • C++ Standard: Toolchain Default
    • Exceptions Support (-fexceptions) checked off
    • Runtime TYpe Information Support (-frtti) checked off
  6. Finish

Copy libnode’s header files¶

To access libnode’s Start() entrypoint, the libnode’s header files are required.

Create the libnode/ folder inside the project’s app/ folder.

In the downloaded zip file, you can find the header files inside the include/ path. Copy this folder to app/libnode/include . If it’s been done correctly you’ll end with the following path for the node.h header file: app/libnode/include/node/node.h

In app/CMakeLists.txt add the following line to add libnode’s header files to the CMake include paths:

Add native JNI function to start node.js¶

Edit app/src/main/cpp/native-lib.cpp to add the required include files:

Convert the existing stringFromJNI function into the startNodeWithArguments function, which takes a Java String array, converts it into a libuv friendly format and calls node::Start . The function’s signature has to be adapted to the chosen organization/application name. Use the already existing stringFromJNI function as a guide. In this sample’s case, it meant changing from:

The final native-lib.cpp looks like this:

Call startNodeWithArguments from Java¶

A few changes are required in the application’s main file MainActivity.java .

Load libnode.so:¶

Instruct Java to load the libnode.so library by adding System.loadLibrary(«node»); to MainActivity.java after System.loadLibrary(«native-lib»); .

The prefix lib and the suffix .so in libnode.so are omitted.

Remove references to stringFromJNI ¶

Remove the references to the stringFromJNI function (which we have replaced in native-lib.cpp ), by deleting the following snippets:

Start a background thread to run startNodeWithArguments ¶

The app uses a background thread to run the Node.js engine.

Currently, only a single instance of the Node.js runtime can be started within an application. Restarting the engine after it has finished running is also not supported.

The node code is a simple HTTP server on port 3000 that returns process.versions . For semplicity, the node code is embedded in the MainActivity.java file:

Add a reference to the startNodeWithArguments function, the Java signature is public native Integer startNodeWithArguments(String[] arguments); .

The MainActivity class looks like this at this point:

Specify required permissions in the manifest¶

Since the app runs an HTTP server, it requires the right permissions in app/src/main/AndroidManifest.xml . Add the following line under the tag:

Add libnode.so to the project¶

Copy the library files¶

In the Android Studio Project, there should be a libnode/ folder inside the project’s app/ folder, created in a previous instruction. Copy the bin/ folder from inside the downloaded zip file to app/libnode/bin . If it’s been done correctly you’ll end with the following paths for the binaries:

  • app/libnode/bin/arm64-v8a/libnode.so
  • app/libnode/bin/armeabi-v7a/libnode.so
  • app/libnode/bin/x86/libnode.so
  • app/libnode/bin/x86_64/libnode.so

Configure CMake¶

In app/CMakeLists.txt specify the native shared library to import and its location:

Add libnode to the already existing target_link_libraries :

Configure the app’s gradle settings¶

In app/build.gradle , some changes have to be made to correctly build and package the application.

We have to instruct gradle to only package native code for the supported architectures, by adding an ndk clause inside defaultConfig :

The shared library was built using the libC++ STL, therefore the ANDROID_STL=c++_shared definition has to be passed inside the cmake clause in defaultConfig with arguments «-DANDROID_STL=c++_shared» :

Configure gradle to override its default sourceSets to include the libnode.so folder path, in the android section:

Add simple UI for testing¶

At this point, it’s already possible to run the app on an Android device and access the HTTP server from any device connected to the same local network. If the Android device’s IP is point the browser at .

However, the sample also comes with the UI to query the local HTTP server and show the response.


You may also like...