2013-05-10 58 views
6

我只是在NodeJS上嘗試一些代碼,我是NodeJS的新手。我寫了下面的代碼塊。在nodeJS中給編碼錯誤

var fs = require('fs'), 
    os = require('os'); 

var filename = 'Server.ini'; 
var serverData = os.hostname() + "\n" + os.platform() + "\n" + os.type() + "\n"; 

fs.existsSync(filename, function(exists) { 
    if(exists) { 
     console.log("1. " + filename + " file found. Server needs to be updated.") 

     fs.unlinkSync(filename, function(error) { 
      if(error) throw error; 
      console.log("2. " + filename + " is been unlinked from server."); 
     }); 

    } else { 
     console.log("1. " + filename + " not found."); 
     console.log("2. Server needs to be configured."); 
    } 
}); 

fs.openSync(filename, "w+", function(error) { 
    if(error) throw error; 
    console.log("3. " + filename + " file is been locked."); 
}); 

fs.writeFileSync(filename, serverData, function(error) { 
    if(error) throw error; 
    console.log("4. " + filename + " is now updated."); 

    fs.readFileSync(filename, 'utf-8', function(error, data) { 
     if(error) throw error; 

     console.log("5. Reading " + filename + " file"); 
     console.log("6. " + filename + " contents are below\n"); 
     console.log(data); 
     console.log("-------THE END OF FILE-------"); 
    }); 
}); 

我已編輯的代碼,增加了同步,但現在它給我以下錯誤:

D:\NodeJS\fs>node eg5.js 

buffer.js:382 
     throw new Error('Unknown encoding'); 
      ^
Error: Unknown encoding 
    at Buffer.write (buffer.js:382:13) 
    at new Buffer (buffer.js:261:26) 
    at Object.fs.writeFileSync (fs.js:758:12) 
    at Object.<anonymous> (D:\NodeJS\fs\eg5.js:28:4) 
    at Module._compile (module.js:449:26) 
    at Object.Module._extensions..js (module.js:467:10) 
    at Module.load (module.js:356:32) 
    at Function.Module._load (module.js:312:12) 
    at Module.runMain (module.js:492:10) 
    at process.startup.processNextTick.process._tickCallback (node.js:244:9) 

D:\NodeJS\fs> 

這有什麼錯在我的代碼就UTF8!

回答

7

readFileSync不需要回撥。我想你想用readFile代替。

對於writeFileSync,您也有同樣的問題。當同步使用IO功能時,被稱爲完成的回調沒有任何意義。最好使用異步函數(沒有「同步」),注意他們採取不同論點的事實。

而且文檔總是提到"utf8"而不是"utf-8",我不知道是否支持後者。

+0

更重要的是,writeFileSync並不需要一個回調。但是,它確實需要編碼。 – Brandon 2013-05-10 13:13:29

+0

是啊,'utf-8'看起來被支持:https://github.com/joyent/node/blob/5a5a98d0d8281f6901b7e9dac285d59ab3e39b95/lib/buffer.js#L126 – dule 2014-07-11 22:57:19

3

按照node.js的API文檔,writeFileSync接受3個參數:

  1. 文件名寫入到
  2. 數據投入到文件
  3. 可選包含的對象的選擇,其中的一個被編碼。

它沒有指定回調。只有異步版本需要回調。

http://www.nodejs.org/api/fs.html#fs_fs_writefilesync_filename_data_options

試試這個,而不是你writeFileSync塊:

fs.writeFileSync(filename, serverData, { encoding: 'utf8'}); 
console.log("4. " + filename + " is now updated."); 

var contents = fs.readFileSync(filename, 'utf8'); 
console.log("5. Reading " + filename + " file"); 
console.log("6. " + filename + " contents are below\n"); 
console.log(contents); 
console.log("-------THE END OF FILE-------");