2014-07-08 24 views
0

我想在我的文件系統中操作多個圖像(imagemagick的轉換命令)。圖像的數量將是動態的,但在這個例子中讓我們使用8.這些圖像都不依賴於彼此,所以我不想調用8個同步exec s(execSync)。Node.js獲取回調中的Exec參數/命令

當前代碼:

var exec = require('child_process').exec, 
    outfile = 'finename123', 
    jsonreturn = [], 
    done = function(){ 
     //all images done move on. 
    }, 
    i = 1; 
for(; i <= 8; i++){ 
    var angle = (i - 1) * 45, 
     bg = __dirname + '/../contentRam/pov/mug11-' + angle + '.png', 
     child = exec('convert ' + bg + ' ' + outfile + i + '.png -compose darken -resize 400x400 -composite png:-', { 
      encoding: 'binary', 
      maxBuffer: 5000 * 1024 
     }, function(error, stdout, stderr){ 
      jsonreturn.push({ 
       src: 'data:image/png;base64,' + new Buffer(stdout, 'binary').toString('base64'), 
       angle: angle 
      }); 

      console.log(angle); 

      if(jsonreturn.length === 8){ 
       done(); 
      } 
     }); 
} 

正如你可以看到我的基本問題是,angle永遠是(在這種情況下315)的最後一個,因爲它完成了for任何回調的運行之前。有沒有什麼方法可以將數值與數據一起傳遞exec正在返回到回調中,以便我知道哪個文件剛剛完成而沒有使其同步?我已經研究過能夠獲取參數或在回調中使用exec調用的整個命令,但我沒有運氣。我也研究了imagemagick的convert命令的額外參數來傳遞額外的數據,也沒有運氣。

我能想到的唯一的另一件事是讓for循環不運行exec而是寫入一個字符串。因此,從child =exec末尾的所有內容都將是一個字符串。一旦完成,每個字符串exec的將在回調中具有正確的參數正確的數據,因爲此時它不是依靠回調之外的i來查看它在哪個exec上,回調字面上寫出它需要執行的方式。這意味着將會有(在這種情況下)8個不同的exec功能與回調,並在所有字符串將是eval版。我無法手動執行此操作,因爲存在動態數量的圖像(有時是8,其他時間是3)。

回答

1

您可以使用map或任何其他並聯機器人方法從async庫:

var async = require('async') 
    , exec = require('child_process').exec 
    , files = ['file1.txt', 'file2.txt'] 

async.map(files 
    , function (file, callback) { 
    // you get the context of each file 
    exec('exec some command with your file', {} , function(error, stdout, stderr){ 
     // you can use the same file reference 
     callback(null, { 
     src: '' // your buffer 
     , angle: files.indexOf(file) * 20 // calculate angle based on the current file 
     }) 
    }) 
    } 
    , function (err, results) { 
    // results have all {src,angle} items 
    }) 
+0

這很好,謝謝。 –

1

檢查async庫。特別是async.waterfall方法。我認爲這正是你需要的。

+0

感謝您的答覆。糾正我,如果我錯了,但'async.waterfall'基本上允許從1異步功能傳遞數據到下一個等等。這基本上使每個異步函數不是同時運行,而是按順序運行(這與我想要做的相反)。我的問題不是將數據從一個異步函數傳遞到另一個異步函數。我的問題是,在每個回調本身內部,我不知道這個回調屬於哪個'exec'命令,所以我不知道該完成哪個文件(因爲即使它們開始以便它們*可以完成訂購)。 –

+0

你對'async.waterfall'說得對。 那麼,你可以嘗試使用'async.parallel'來滿足你的需求。希望能幫助到你。 –

+0

+1指向我正確的庫。 –