iOS 使用node js 搭建簡單的本地服務器


一.前提:基於iOS 項目 調用,使用了第三方框架NodeMobile。技術說明關鍵是 應用生命整個周期只能在應用啟動時候開辟的一個線程里申請 一個 node  js 資源。如果終止了運行,重啟是不支持的。 

   “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.”

二.目標:能夠跑起node js  本地服務,讀取本地一段 json.

             來實現 讓客戶端模擬服務請求,方便在 服務端 和客戶端等 多端 同步開發,減少阻塞依賴。

三.集成node js 到項目步驟

(1)pod 'NodeMobile', :git => 'https://github.com/janeasystems/nodejs-mobile.git' 引入SDK  (或者參考demo github 手動引入也可)

(2)此時運行程序會報錯,提示該第三方庫 不支持bitcode設置,需要在 BuildSetting 里 bitcode 布爾設置項改為NO  ,項目能正常跑起。

(3)按照demo 模擬”本地js”  一路暢通

(4)模擬 node js 會閃退, 原因 a.不支持npm 命令 b.沒有引入main.js 中 引用的節點 node js”left - pad”

  (5) 安裝npm 參考2

       a.這里使用 場景是 在mac本上操作 iOS framework Node js

       b.需要支持brew命令,因為我之前安裝過,這個過程省略了

         具體為參考3

       c.使用brew命令下載 CMake  : brew install cmake

   (6) 

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

git clone https://github.com/janeasystems/nodejs-mobile

cd nodejs-mobile

git checkout mobile-master 

      2) Run the helper script: 配置node js 在Xcode 項目中使用

./tools/ios_framework_prepare.sh

 

(7)在項目中,藍色文件作為資源使用,創建文件路徑要選擇create folder 才行. 防止 [[NSBundle mainBundle] pathForResource:@"nodejs-project/main.js" ofType:@""]; 找不到資源

(8)在項目 nodejs-project 內 執行命令  npm install 

(9)添加 main.js 中引用的lef pad 節點   還是在(8)文件夾內執行 命令 npm install left-pad

  至此,基本整個項目就跑通了。。。

四.客戶端代碼部分:

  

#import "AppDelegate.h"
#import "NodeRunner.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)startNode1 {
    NSArray* nodeArguments = [NSArray arrayWithObjects:
                              @"node",
                              @"-e",
                              @"var http = require('http'); "
                              " var versions_server = http.createServer( (request, response) => { "
                              "   response.end('Versions: ' + JSON.stringify(process.versions)); "
                              " }); "
                              " versions_server.listen(3000); "
                              ,
                              nil
                              ];
    [NodeRunner startEngineWithArguments:nodeArguments];
}

- (void)startNode {
    NSString* srcPath = [[NSBundle mainBundle] pathForResource:@"nodejs-project/main.js" ofType:@""];//這個路徑 是藍色文件夾才行
    NSArray* nodeArguments = [NSArray arrayWithObjects:
                              @"node",
                              srcPath,
                              nil
                              ];
    [NodeRunner startEngineWithArguments:nodeArguments];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//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. NSThread
* nodejsThread = nil; nodejsThread = [[NSThread alloc] initWithTarget:self selector:@selector(startNode) object:nil ]; // Set 2MB of stack space for the Node.js thread.
//The iOS node runtime expects to have 1MB of stack space available. Having 2MB of stack space available is recommended.
    [nodejsThread setStackSize:2*1024*1024];
    [nodejsThread start];
    return YES;
}

 

#import "ViewController.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, self.view.frame.size.width, 88);
    btn.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(myButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)myButtonAction:(id)sender
{
    NSString *localNodeServerURL = @"http:/127.0.0.1:3000";//Localhost 代表的是本機的位置, 通常其對應的IP 是127.0.0.1 端口號3000根據需要自定義不被占用閑置的就好
    NSURL  *url = [NSURL URLWithString:localNodeServerURL];
    NSString *versionsData = [NSString stringWithContentsOfURL:url];
    if (versionsData) {
        NSLog(@"%@",versionsData);//這里會輸出目標結果 eg json
    }
}

藍色文件夾創建文件路徑要選擇create folder 才行.(nodejs-project 文件夾)

nodejs-project文件夾里面main.js 內容

var http = require('http');       //http 模塊
var leftPad = require('left-pad');//left pad 模塊 

//
var  fs = require('fs');       //文件模塊
var  path = require('path'); //系統路徑模塊

var  jsonFile = './package.json';
var file = path.join(__dirname, jsonFile) //文件路徑,__dirname為當前運行js文件的目錄
//讀取本地指定的一個json 文件並s回執
var versions_server = http.createServer((request, response) => {//開啟一個本地服務
    console.log('xx' + request);
    fs.readFile(file,'utf8',function(err,data){
        response.end(data); //這里輸出讀取路徑jsonFile的json文件
}) }); /* var versions_server = http.createServer( (request, response) => { response.end('Versions: ' + JSON.stringify(process.versions) + ' left-pad: ' + leftPad(42, 5, '0')); }); */ 
versions_server.listen(
3000); //監聽預定使用的端口號3000

 

參考 

       1.https://code.janeasystems.com/nodejs-mobile/getting-started-ios

       2.https://github.com/janeasystems/nodejs-mobile

       3.https://brew.sh/

       4.https://blog.csdn.net/lihefei_coder/article/details/81453716

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM