gpt4 book ai didi

node.js - 在nodeJS中给出编码错误

转载 作者:IT老高 更新时间:2023-10-28 23:25:01 26 4
gpt4 key购买 nike

我只是在 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 不接受回调。我猜你想改用 readFile

writeFileSync 也有同样的问题。同步使用 IO 函数时,完成时调用的那些回调没有意义。最好使用异步函数(不带“Sync”),注意它们采用不同的参数。

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

关于node.js - 在nodeJS中给出编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com