NativeScript:require(' child_process')在运行" tns run ios时出错--memulator"

时间:2016-12-13 06:07:42

标签: node.js npm nativescript child-process

我有一个像这样的实验代码来测试从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);
    }
});

当我使用" tns运行ios --emulator"来测试此应用时,它会出现如下错误:

  

file:///app/views/login/login.js:1:89:JS ERROR错误:无法找到模块' child_process'。计算路径' / 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'

我的问题是:我该如何解决这个问题?我应该做什么" npm install child_process"在应用程序的目录?但是当我在Google上搜索解决方案时,我读到它应该自然地包含在node_modules ...

我找到了一个child_process模块​​: 的/ usr /本地/ LIB / node_modules / nativescript / LIB /通用

但正如错误消息所示,当我使用tns命令执行应用程序时,它不包括在内。有人能告诉我我错过了什么吗?

版本信息: npm:3.10.10 节点:7.2.1 tns:2.4.2

1 个答案:

答案 0 :(得分:2)

您看到的child_process是NativeScript CLI for Node的child_process的包装器。

NativeScript中没有child_process,因为该概念与移动环境(Android / iOS)无关。 例如,Node JS跨平台工作的原因是因为它的引擎为每个支持的平台都有类似的功能实现(文件系统,http,子进程)。

使用node的child_process(显式安装并要求它)可能不起作用,因为没有移动设备的内部实现。

如果您想在后台执行某些操作,请考虑使用NativeScript的Workers。

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

编辑:

如果没有可用的插件,您可以使用底层的本机API来调用设备的shell。

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

nativescript网站上的文档可以帮助您将objC / Java代码“转换”为JavaScript,尽管它非常简单。

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