需求背景:
在利用casperjs 在爬資料的時候需要爬多個資料,如果所有的的指令碼寫在一個js 裡面,就不利於維護,以及後期的新功能的增加。現在就是要把一個類只做一件事情,例如 Hello.js 只負責列印 Hello。這樣就會涉及到需要同時啟動幾個任務。例如,baidu.js 負責爬百度的資料,google.js 只負責爬谷歌的資料。現在需要用一條指令碼同時啟動兩個檔案去爬資料。
需求分析:
1.casperjs 在終端 通過 敲 casperjs xx.js 來執行的,呼叫了python 的環境。本質上執行了exec 的命令,如果在linux 系統上的話還需要給執行的檔案加相對應的許可權。
2.首先讓index.js 可以直接執行 a.js
3.利用node 子執行緒去啟動
a.js 簡單寫一句:
console.log('hello')
複製程式碼
index.js:
var exec = require('child_process').exec;
var child = exec('node ' + 'a.js', function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});
複製程式碼
b.js
console.log('I am b.js');
複製程式碼
同時執行 a.js 和 b.js
var exec = require('child_process').exec;
var child = exec('node ' + 'a.js', function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});
var child2 = exec('node ' + 'b.js', function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
});
複製程式碼
4.通過shelljs 模組來執行shell 指令碼 需要安裝
npm install --save shelljs
複製程式碼
例子:
var shell = require("shelljs");
shell.exec("node a.js ");
複製程式碼
存在問題,解決了shell 命令呼叫,引數呼叫還欠缺
5.通過yargs 模組,可以解決處理命令列引數
var argv = require('yargs').argv;
console.log('url is ', argv.url)
複製程式碼
執行:
node yargs.js --url=www.baidu.com
複製程式碼
解決方案:
1.通過require('child_process').exec;
呼叫
2.通過 shelljs
模組
3.通過 yargs
模組呼叫
總結:
可以根據業務具體需求,來決定用哪一種解決方案,看那一個更適合自己的團隊。