2017-11-11 263 views
0

例如輸出如果孩子的NodeJS過程類似執行:如何分析標準輸出

exec("find /path/to/directory/ -name '*.txt'", callback); 

如何可以解析在我的回調函數的流輸出到一個數組中得到的東西,像這樣?

['file-1.txt', 'file-2.txt', 'file-3.txt', ...] 

電流輸出就像下面:

path/to/file-1.txt 
path/to/file-2.txt 
path/to/file-3.txt 

感謝您的幫助

+0

不回調返回這裏什麼參數? – wrangler

+0

回調函數(誤差,標準輸出,標準錯誤){...} 返回的輸出看起來像這樣: '路徑/到/ file1.txt' '路徑/到/ file1.txt' –

+0

返回的輸出的回調如下所示: 'path/to/file1.txt'
'path/to/file2.txt'
'path/to/file3.txt' –

回答

0
const exec = require('child_process').exec; 
exec("find /path/to/directory -name '*.txt'", (error, stdout, stderr) => { 
    if (error) { 
     // handle error 
    } else { 
     var fileNames = stdout.split('\n').filter(String).map((path) => { 
      return path.substr(path.lastIndexOf("/")+1); 
     }); 
     console.log(fileNames); // [ 'file1.txt', 'file2.txt', 'file3.txt' ] 
    } 
}); 

const exec = require('child_process').exec; 
exec("ls /path/to/directory | grep .txt", (error, stdout, stderr) => { 
    if (error) { 
     // handle error 
    } else { 
     var fileNames = stdout.split(/[\r\n|\n|\r]/).filter(String); 
     console.log(fileNames); // [ 'file1.txt', 'file2.txt', 'file3.txt' ] 
    } 
}); 
相關問題