2012-08-16 76 views
2

我知道這樣的問題,如How to append to a file in Node?追加到一個已經存在的文件nodejs?

但是,那些沒有做我所需要的。我所擁有的是在啓動nodejs之前已經包含文本的文本文件,然後我希望節點在我的文件末尾添加文本。

但是,在上面鏈接的問題中使用方法會覆蓋我的文件的內容。

我還發現我可以在我的fs.createWriteStream的選項中使用start:number,所以如果我想知道我的舊文件結束的位置,我可以使用它來追加,但是如何在不必讀出整個文件並計算其中的字符?

回答

1

我還發現文檔混淆,因爲它沒有告訴你如何實際設置該命令(或者你可能需要在添加之前讀入文件)。

這是一個完整的腳本。填寫你的文件名並運行它,它應該工作!這是腳本背後的邏輯video tutorial

var fs = require('fs'); 

function ReadAppend(file, appendFile){ 
    fs.readFile(appendFile, function (err, data) { 
    if (err) throw err; 
    console.log('File was read'); 

    fs.appendFile(file, data, function (err) { 
     if (err) throw err; 
     console.log('The "data to append" was appended to file!'); 

    }); 
    }); 
} 
// edit this with your file names 
file = 'name_of_main_file.csv'; 
appendFile = 'name_of_second_file_to_combine.csv'; 
ReadAppend(file, appendFile); 
相關問題