code-prettify

2014年5月7日 星期三

Write to file - Node.js

將文字新增在原本檔案之後,參考網路範例後改寫如下:

var fs = require('fs');

// 宣告函式
var writelog = function(filepath, log){
  fs.open(filepath, 'a', 666, function( e, id ) {
    fs.write(id, log, null, 'utf8', function(){
    fs.close(id, function(){
      //console.log('file closed');
    });
    });
  });
};

// 目錄要事先建好喔
var filepath = 'C:/Test/I-Love-You.txt'
var message = 'Hello Kitty!'

// 呼叫函式
writelog(filepath, message + '\r\n');


參考來源:
How to append to a file in Node?
http://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node