Run nodejs on android

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

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

Termux

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. Сделать это очень просто:

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

Express

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

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

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

Nodemon

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

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

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

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

MongoDB

К сожалению, у меня не получилось запустить 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.

Читайте также:  Android studio положение экрана

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
Читайте также:  Gihosoft free android data recovery

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 192.168.1.100 point the browser at http://192.168.1.100:3000/ .

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

Источник

How to Run Node.JS in an Android App

This quick tutorial will run you through running Node.js in an Android app.

Join the DZone community and get the full member experience.

Hello geekers, Android is more customizable and easy to use mobile operating system nowadays. And in upcoming growing language node.js has their great power which uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

And for a developer, it would be great to integrate Node.Js with their Android application to use that power with existing application.

Here is the library which do it same for you named as Node-Android library which is used to run Node.js on Android by rewrite Node.js in Java with the compatible API.

Download this library from here

Now let’s dive in with the process of integration and features.

Build

Clone the code, open Android Studio (1.*) and import the project.

For Eclipse ADT user, refer to this.

Javascript code injection

Features

  • Node.js 0.10.x compatible API
  • Multi-threading: run separate node context in Java thread
  • libUV native support
  • Timer, set/clear Timeout/Interval
  • EventEmitter
  • Stream
  • HttpParser(rewrite http-parser.c in java)
  • HTTP
  • HTTPP(run http over udp)
  • TCP
  • UDT(udp transport)
  • DNS
  • URL
  • IPv6
  • for API usage, check
  • WebSocket/WebSocketServer supported, check
  • Connect middleware
  • Crypto: NACL support, public box,secret box,signature/verify
  • SecureWebSocket over NACL

JS Runtime

  1. Rhino supported
  2. Exposed node-android packages: com.iwebpp.node.http, com.iwebpp.node.stream, com.iwebpp.node.net, etc
  3. Exposed node-android classes: com.iwebpp.node.EventEmitter2, com.iwebpp.node.Dns, com.iwebpp.node.Url, etc
  4. Exposed node-android native context in JS standard scope as NodeCurrentContext alias NCC
  5. Exposed Android API: android.util.Log
  6. NodeJS compatible internal modules are available in JS standard scope
  7. Exposed WebSocket classes: com.iwebpp.wspp.WebSocket, com.iwebpp.wspp.WebSocketServer

Published at DZone with permission of Adam Smith . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Run nodejs on android

Node.js for Mobile Apps

This is the main repository for Node.js for Mobile Apps, a toolkit for integrating Node.js into mobile applications.

Resources for Newcomers

This is the central repository for reporting all issues related to the Node.js for Mobile Apps project, including issues pertaining to the React Native and Cordova plugins.

The core library source code is in this repo. If you are looking for the source code for the plugins, you can find it at:

  1. To provide the fixes necessary to run Node.js on mobile operating systems.
  2. To investigate which features need to be added to Node.js in order to make it a useful tool for mobile app development.
  3. To diverge as little as possible from nodejs/node, while fulfilling goals (1) and (2).
Читайте также:  Какие видеокодеки поддерживает андроид

Documentation can be found on the project website. Sample code is available in the samples repo.

Disclaimer: documentation found in this repository is currently unchanged from the parent repository and may only be applicable to upstream node.

Prerequisites to build the Android library on Linux Ubuntu/Debian:

Basic build tools:

Install curl and unzip (needed to download the Android NDK):

Install Android NDK r21b for Linux:

Choose a location where you want to install the Android NDK and run:

It will create a android-ndk-r21b folder. Save that path for later.

Prerequisites to build the Android library on macOS:

Run git in a terminal window, it will show a prompt to install it if not already present. As an alternative, installing one of these will install git :

Install Android NDK r21b for macOS:

Choose a location where you want to install the Android NDK and run:

It will create a android-ndk-r21b folder. Save that path for later.

Building the Android library on Linux or macOS:

1) Clone this repo and check out the mobile-master branch:

2a) Using the Android helper script:

The tools/android_build.sh script takes as first argument the Android NDK path (in our case is

/android-ndk-r21b ). The second argument is optional and is the target architecture, which can be one of the following: arm , x86 , arm64 or x86_64 . If no target architecture is provided, it will build all available architectures. Run:

When done, each built shared library will be placed in out_android/$(ARCHITECTURE)/libnode.so .

2b) Configure and build manually:

Run the android-configure script to configure the build with the path to the downloaded NDK and the desired target architecture.

Start the build phase:

This will create the Android armeabi-v7a shared library in out/Release/lib.target/libnode.so .

Prerequisites to build the iOS .framework library on macOS:

Xcode 11 with Command Line Tools

Install Xcode 11 or higher, from the App Store, and then install the Command Line Tools by running the following command:

That installs git , as well.

To install CMake , you can use a package installer like Homebrew.

First, install HomeBrew , if you don’t have it already.

Then, use it to install CMake :

Building the iOS library using CocoaPods:

Add this to your Podfile :

Building the iOS .framework library on macOS:

1) Clone this repo and check out the mobile-master branch:

2) Run the helper script:

That will configure gyp to build Node.js and its dependencies as static libraries for iOS on the arm64 and x64 architectures, using the v8 engine configured to start with JIT disabled. The script copies those libraries to tools/ios-framework/bin/arm64 and tools/ios-framework/bin/x64 , respectively. It also merges them into static libraries that contain strips for both architectures, which will be placed in tools/ios-framework/bin and used by the tools/ios-framework/NodeMobile.xcodeproj Xcode project.

The helper script builds the tools/ios-framework/NodeMobile.xcodeproj Xcode project into three frameworks:

  • The framework to run on iOS devices: out_ios/Release-iphoneos/NodeMobile.framework
  • The framework to run on the iOS simulator: out_ios/Release-iphonesimulator/NodeMobile.framework
  • The universal framework, that runs on iOS devices and simulators: out_ios/Release-universal/NodeMobile.framework

While the universal framework is useful for faster Application development, due to supporting both iOS devices and simulators, frameworks containing simulator strips will not be accepted on the App Store. Before trying to submit your application, it would be advisable to use the Release-iphoneos/NodeMobile.framework in your submission archive or strip the x64 slices from the universal framework’s binaries before submitting.

Please see the TESTING.md file in the doc_mobile folder in this source distribution.

Please see the CONTRIBUTING file in the doc_mobile folder in this source distribution.

Источник

Оцените статью