D
D
Djahar2015-11-10 19:52:42
Node.js
Djahar, 2015-11-10 19:52:42

fs module in Node.Js, why did it return undefined?

Hello. I am a beginner in learning Node JS modules. I ran into a problem like this, first the code:

var http = require('http');
var fs = require('fs');
http.createServer(function(req, res){
    res.writeHead(200, {'Content-type':'text-html; charset=utf-8'});
    res.write("Hello World ");
    fs.readFile('index.html', function(err, data){
        res.write(decodeURIComponent(data));
        res.end();
    });
}).listen(8080);

So res.write(decodeURIComponent(data)) returns undefined.
I don't even know what the problem is. Help me please. Maybe it's not connected correctly?
The path to the file is correct. I think the code does not need to be commented. The goal is to take the content of the html file and output it. The content of the html file is as follows. <hr><strong>Message</strong>
That is, the following is displayed in the browser: "Hello undefined".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dnech, 2015-11-10
@Dnech

It's strange, but your code works fine for me ...
I would check for you what is in err, try to make the path to the file relative and generally see what is in the variables ...
maybe like this:

fs.readFile('./index.html', function(err, data){
    console.log('readFile err', err);
    console.log('readFile data', data);
    console.log('readFile decData', decodeURIComponent(data));
        res.write(decodeURIComponent(data));
        res.end();
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question