给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!

readFileSync不需要callback。 我想你想用readFile来代替。

你有writeFileSync相同的问题。 这些被称为完成的callback在同步使用IOfunction时没有任何意义。 最好使用asynchronous函数(没有“同步”),注意事实他们采取不同的论点。

而且文件总是提到"utf8" ,而不是"utf-8" ,我不知道后者是否被支持。

根据node.js API文档,writeFileSync需要3个参数:

  1. 要写入的文件名
  2. 数据存入文件
  3. 可选对象包含选项,其中之一是编码。

它没有指定callback。 只有asynchronous版本需要callback。

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-------");