我使用這個異步遞歸函數遍歷目錄的文件和文件夾,當找到.css文件時,我將數據追加到名爲'common.css'的文件中。異步追加數據到文件
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null);
list.forEach(function(file) {
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
minimizer(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null);
});
} else if(file) {
fs.open('common.css', 'a', 666, function(err, id) {
fs.write(id, 'hello', null, 'utf8', function(){
fs.close(id, function(){
console.log('file closed');
});
});
});
}
if (!--pending) done(null);
});
});
}); }
問題是,我覺得有些時候,函數的幾個實例同時寫入文件,這是異步的。有沒有什麼辦法可以控制這種流量並排列寫作任務?
此代碼的目的是合併目錄中找到的.css文件。我不能在這個項目中使用外部工具。
編輯回答:那麼,爲了這個目的,我可以收集所有.css文件的路徑,我想要合併,並且在我擁有它們之後,調用syncronous函數來編寫它們。
這就是
VAR的結果= []
是有什麼。我剛剛意識到這一點。
在這個例子中你開擴,並在該目錄中common.css書面方式招呼每一個文件,所以如果你有3個文件,你會寫「hellohellohello」。這是你的真實代碼嗎?爲此目的,您可以獲得文件數量,然後只打開和寫入一次「hello」N次。 –