2016-07-31 102 views
0

我正在嘗試爲目錄中的每個文件寫入一些內容。我的想法是讀取目錄並列出目錄中的所有文件。fs.appendfile在foreach循環中不起作用

然後,對於每個文件,將文件的位置作爲字符串追加到文本文件中。

例如:目錄包含2個文件,Sample2.content1.txt,Sample2.content2.txt。

我想讀取sample1.content1.txt並將其在位置文件中的位置寫爲c:\ sample1.txt。

在文件中的文本的格式爲

Page 0 -/text.php 
Page 1 -/60893.php 
Page 2 -/1189.php 
Page 3 -/20389.html 

我工作的這一點,但我堅持在爲什麼追加文件不寫入文件內容。

var fs = require('fs'); 
fs.readdir('C:/Users/Administrator/Desktop/Project/output',function(err,data) 
{ 
    if(err) throw err; 
    data.forEach(function(file){ 
     //console.log('C:/Users/Administrator/Desktop/Project/output'+file) 
     fs.appendFile('C:/Users/Administrator/Desktop/Project/output'+file,'appending this text to file','utf8',(err)=>{if(err) throw err; console.log('data was appended to '+file)}) 
    }); 
}); 

運行這並沒有給我任何錯誤和執行console.log回報: 數據附加到sample2.content1.txt 數據附加到sample2.content2.txt

我婉執行多個在附加字符串後對文件執行操作,即解析文件中的文本並將其轉換爲JSON格式等。

希望你能幫助我。JS和Node的新手。

問候, 潔

+0

這是一個普遍不好的做法,因爲你是在一個循環中運行多個異步操作,並期待他們以正確的順序進行排序,但也不能保證他們會按照正確的順序去。 – jfriend00

+0

任何關於如何以正確的方式解決這個問題的建議都會很棒。我是Node和JS的新手,我只是在嘗試。 – user1222256

回答

0

我的錯......只是覺得...

我一直在尋找在錯誤的文件夾中的數據是越來越附加到文件outputsample2.content1.txt,因爲我錯過了'/' after output/

所以它應該是

fs.appendFile('C:/Users/Administrator/Desktop/Project/output/'+file,'appending this text to file','utf8',(err)=>{if(err) throw err; console.log('data was appended to '+file)}) 

希望有人會發現它有用。

問候, 潔