0

I have a experiment code like this just to test calling a child process from NativeScript app (myapp/app/views/login/login.js):

var exec = require('child_process').exec;

exec('ls', function (error, stdout, stderr) {
    if(stdout){
        console.log('stdout: ' + stdout);
    }
    if(stderr){
        console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('Exec error: ' + error);
    }
});

when I test this app with "tns run ios --emulator", it gives an error like this:

file:///app/views/login/login.js:1:89: JS ERROR Error: Could not find module 'child_process'. Computed path '/Volumes/xxxx/Users/xxxx/Library/Developer/CoreSimulator/Devices/392A8058-694B-4A5D-B194-DF935815ED21/data/Containers/Bundle/Application/2822CD65-4E4D-443C-8272-135DB09353FC/sampleGroceries.app/app/tns_modules/child_process'.

My question is: how can I resolve this? Should I do "npm install child_process" on the app's directory? But while I was searching for solutions on Google, I read that it should be naturally included from node_modules...

I find a child_process module in: /usr/local/lib/node_modules/nativescript/lib/common

but as the error message says, it isn't included when I execute the app with tns command. Could someone tell me what I'm missing?

version info: npm: 3.10.10 node: 7.2.1 tns: 2.4.2

Mumi
  • 95
  • 10

1 Answers1

2

The child_process that you are seeing is a wrapper in the NativeScript CLI for Node's child_process.

There is no child_process in NativeScript as the concept is not relevant in mobile environments (Android/iOS). The reason Node JS works cross-platform for example, is because its engine has analogous feature implementation (file-system, http, child process) for each of the supported platforms.

Using node's child_process (installing it explicitly and requiring it) will likely not work, as there is no in-house implementation for mobile devices.

If you would like to perform something in the background, consider using NativeScript's Workers.

http://docs.nativescript.org/angular/core-concepts/multithreading-model.html

Edit:

If there isn't a plugin already that is readily available, you could use the underlying native API to call to the device's shell.

Android: execute shell command from android iOS (Objective C): Cocoa Objective-C shell script from application?

Docs on the nativescript site are available that should help you in 'translating' objC/Java code to JavaScript, though it is pretty straightforward.

http://docs.nativescript.org/runtimes/android/marshalling/java-to-js http://docs.nativescript.org/runtimes/ios/marshalling/Marshalling-Overview

Community
  • 1
  • 1
pkanev
  • 1,486
  • 1
  • 12
  • 20
  • Thank you, I was stuck at this thing for 2 nearly days and couldn't figure it out on my own... what I wanted to do doesn't need to perform in the background for now, I just wanted to execute some common shell commands on iOS and Android. Is it possible? – Mumi Dec 14 '16 at 09:55