我刚从node.js开始,我遇到了appendFile,它将内容附加到文件的末尾,但是当我执行它时,我的代码id将内容完全替换为数据。
这是密码。
var http = require('http');
var file = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var fd = file.open('default.html','w',function(err){
if(err)throw err;
});
file.appendFile('default.html',"<p>Hi,this to inform you that i really don't care</p>",function(err){});
return res.end();
}).listen(8080);defalult文件是
<!doctype>
<html lang="en">
<head>
<title>File</title>
</head>
<body>
<h1>
Hi, EveryOne
</h1>
</html>我得到的输出是
<p>Hi,this to inform you that i really don't care</p>有谁能告诉我为什么会发生这种事,或者我做错了什么?
发布于 2018-11-09 06:34:40
因为您已经在“w”(即写模式)中打开了文件,然后对其执行操作。您实际上不需要在追加文件之前打开它。
var fd = file.open('default.html','w',function(err){
if(err)throw err;
});我看不出来,你用它做任何有用的事情,所以这段代码是不必要的。如果您确实需要它,那么以“追加”模式打开文件,将'w'替换为'a',并记住也关闭该文件。
但是,正如我所说的,您可以简单地使用该方法追加,而不是打开该文件。
https://stackoverflow.com/questions/53220355
复制相似问题