我看了Node.js Documentation而且我没有找到如何应用选项(设置)和带有错误处理的回调函数。而且我必须使用 .writeFileSync(不是异步 .writeFile):
const settings = {
flags: 'w',
encoding: null, //must be null
mode: 0o666,
autoClose: true //not found this option
};
fs.writeFileSync(dest, buff, settings);
在我使用之前:
fs.writeFileSync(dest, buff, function (err) {
if (err) {
...
} else { ... console.log("OK") }
})
但我发现我必须应用 encoding: null, 选项来防止对源数据 (buff) 进行任何修改,否则文件可能会损坏。
编辑: 在得到了惊人的答案和解释之后,我想说我对 Node.js 文档感到困惑: fs.writeFileSync(file, data[, options]) 是
The synchronous version of fs.writeFile().
由于这是 fs,writeFile() 方法的版本,我认为它可以具有相同版本的函数签名...
这是我的最终版本的代码,但是它仍然存在二进制文件解码的问题(可以是任何文件类型)(*顺便说一下,当我尝试使用 Axios.js 时我看到错误:“请求失败,状态代码为 500”:
function download(url, dest, fileName, callback) {
//import http from 'http';
var request = http.get(url, function (response) {
var bodyParts = [];
var bytes = 0;
response.on("data", function (c) {
bodyParts.push(c);
bytes += c.length;
})
response.on("end", function () {
// flatten into one big buffer
var buff = new Buffer(bytes);
var copied = 0;
for (var i = 0; i < bodyParts.length; i++) {
bodyParts[i].copy(buff, copied, 0);
copied += bodyParts[i].length;
}
const settings = {
flags: 'w',
encoding: null, //not applicable / no changes
mode: 0o666
};
try {
fs.writeFileSync(dest, buff, settings);
let msgOK = {
filename: fileName,
status: 'OK',
text: `File downloaded successfully`
}
if (callback) callback(msgOK);
console.log(msgOK.text);
isLoading = false; //IMPORTANT!
} catch (err) {
console.error(err.stack || err.message);
let msgErr = {
filename: fileName,
status: 'ERROR',
text: `Error in file downloading ${err.message}`
}
ERRORS.push(err);
if (callback) callback(msgErr);
}
})
})
}
最佳答案
任何文件系统方法的同步版本都不接受回调,它们会在出错时抛出异常,所以你应该捕获它。
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try {
fs.writeFileSync(dest, buff);
// You don't need callback, the file is saved here
} catch(e) {
console.error(e);
}
fs.writeFileSync
没有设置autoClose
,唯一可用的选项是:
encoding <String> | <Null> default = 'utf8'
mode <Number> default = 0o666
flag <String> default = 'w'
最后但同样重要的是,您应该更新您的 Node 版本,因为 Node.js 4.x end of life不到一周。 (2018-04-30)
关于javascript - 带有选项、回调和错误处理器的 Node.js fs.writeFileSync?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50033461/