0

When I run this as server, and goto localhost:8080 'Saved!' is printed twice in console. And also 'Honey Bee' is appended twice in mynewfile1.txt Why is that?

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 Answers2

2

It's because your browser makes an additional request to fetch favicon.ico. Use curl to make a single HTTP request:

curl http://localhost:8080
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

If you put a return statement at the end of the function, it won't run more than once.

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