2016-12-30 48 views
0

我需要獲取所有名爲templates /的鬍子模板目錄,並使用hogan進行編譯。NodeJS,批處理文件,替代每個文件寫入過多的對象/函數?

從理論上講,假設他們的名字,

file1.mustache file2.mustache file3.mustache

然後我們進行每一個視圖,並將結果保存到輸出目錄名爲build /。

理論上所產生的名字會是這樣,

name.file1 name.file2 name.file3

顯然異步最好的,但我最感興趣的是你會怎麼做這有效?我不能相信唯一的辦法就是做每個文件對象和匿名函數。

+0

爲什麼不直接列出保存模板和處理每個模板的目錄中的所有文件?我想現在還不清楚你實際上在問什麼,而不是明顯的解決方案。另外「爲每個文件寫入過多的對象/函數」是什麼意思?也許展示你正在談論的一些例子。 – jfriend00

回答

2

您可以使用fs-promise模塊Promise.all一起並行輕鬆讀取,處理和寫入文件:

const fsp = require('fs-promise'); 

function processTemplate(filename) { 
    return fsp.readFile(filename, 'utf8') 
    .then((template) => hogan.compile(template)) 
    .then((compiledTemplate) => fsp.writeFile('path/to/compiled', compiledTemplate)); 
} 

fsp.readdir('./templates') 
    .then((files) => Promise.all(files.map(processTemplate))) 
    .catch((error) => console.log(error)); 

雖然我不知道我理解你所說的「每個文件對象的意思和匿名功能「。

相關問題