hadrienj
hadrienj

Reputation: 2003

Is it possible to run a local web server with node.js on Android?

I am constructing a node.js application (node.js for the server side and html/javascript/css for the client side). Here is my server.js file:

var app = require('http').createServer(handler),
  fs = require('fs'),
  static = require('node-static');

// handle web server
function handler (req, res) {
  fs.readFile(__dirname + '/client/client.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

// creating the server ( localhost:8000 )
app.listen(8000);


// Create a node-static server instance to serve the './static' folder
var staticFiles = new static.Server('./static');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        //
        // Serve files!
        //
        staticFiles.serve(request, response);
    }).resume();
}).listen(8080);

I use this as a local server to build my app. On my computer I use the command node server.js in Terminal to run the server and serve my html and javascript files at this address: http://localhost:8000/.

I would like to do the exact same thing on a tablet with android. Is this possible and how to do it?

EDIT: I have seen that maybe this is possible here but I'm not sure that the problem is the same.

Upvotes: 1

Views: 2333

Answers (1)

Josh Wulf
Josh Wulf

Reputation: 4877

I run Node.js on Linux on Android devices. I did it like this:

  1. Install Kingroot from the Play Store to get root on the Android device.
  2. Install Linux Deploy, then use it to install Fedora.
  3. Use Android Terminal to su to root in Android, then run data/data/ru.meefik.com/linuxdeploy/files/bin/linuxdeploy shell to get a root shell in the Linux container.
  4. Change the root password in the Linux container to 'a' (it wouldn't take more than one character for some reason).
  5. Use JuiceSSH to ssh into the Fedora Linux container. Su to root and change the password.
  6. dnf install nodejs npm # install node
  7. npm install -g n # install substack's node version manager
  8. n 5.3.0 # install v5.3.0 of node
  9. mv /usr/sbin/node /usr/sbin/node.orig
  10. mv /usr/sbin/npm /usr/sbin/npm.orig
  11. ln -s /usr/local/bin/node /usr/sbin/node
  12. ln -s /usr/local/bin/npm /usr/sbin/npm

Steps 9 - 12 were necessary because sudo node --version would always return the dnf installed version, rather than the n installed version.

Upvotes: 2

Related Questions