函数在nodejs中调用两次

时间:2017-05-07 08:34:56

标签: node.js

当我将其作为服务器运行时,转到localhost:8080'已保存!'在控制台中打印两次。还有蜜蜂'在mynewfile1.txt中附加两次为什么会这样?

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('Hello World!');

    fs.readFile('head.html', function (err, data) {
        res.write(data);
        res.end();
    });

    fs.appendFile('mynewfile1.txt', 'Honey Bee', function (err) {
        if (err) throw err;
        console.log('Saved!');
    });
}).listen(8080);

2 个答案:

答案 0 :(得分:1)

这是因为您的浏览器makes an additional request要抓取favicon.ico。使用curl发出单个HTTP请求:

curl http://localhost:8080

答案 1 :(得分:0)

如果在函数末尾放置一个return语句,它将不会运行多次。

content = "<p>This is content written to a file</p>";
file_name = "html/fs_test_file.html";
fs.appendFile(file_name, content,
    (err) =>
    {
        if (err) throw err;
        console.log("File created");
        return;
    });
相关问题