0

I have this simple piece of code:

var http = require('http'), fs = require("fs");
function get(p) {
    fs.readFile('.' + p,'utf8', function (err, cont) {
        if  (err) return "EERRRORRRRR";
        else return cont;
    })
}
http.createServer(function (request, response) {
    var path = ((request.url==="/")?"/index.html":request.url);
    console.log(get(path));
}).listen(80);

When I run and connect to the server, it logs undefined...

When I add a "console.log(cont)" like:

    fs.readFile('.' + p,'utf8', function (err, cont) {
        console.log(html)
        if  (err) return "EERRRORRRRR";
        else return cont;
    })

; it logs the correct contents, so why is the function returning undefined? the contents exists...

How would i fix this issue?

The originally context of the code was a simple web server, if you couldn't tell.

3 Answers 3

1

Read about callbacks and asynchronous functions, you can find docs in google

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

// notice new parameter callback
function get(p, callback) {
    fs.readFile('.' + p,'utf8', callback);
}

http.createServer(function (request, response) {
    var path = ((request.url==="/")?"/index.html":request.url);

    // get accepts callback
    get(path, function(err, data){
        if(err){
            response.send('not found');
        } else {
            response.send(data);
        }
    });
}).listen(80); // notice: port 80 requires sudo to run, use better 3000
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I'll further into callback structuring
what are the benefits of using the status and send methods? they don't work in my applications so i just used end...
@WorstForum yeah, they are up to you. status is for rest-apis
0

readFile in node.js is async (as well as almost all other functions). You can't return values from async functions, instead, you need to use a callback function that will be called once the operation ends:

 fs.readFile('.' + p,'utf8', function (err, cont) {
            console.log(html)
            if  (err) return "EERRRORRRRR";
            else handleResponse(cont);
        })

function handleResponse(data){//Do something here}

Comments

0

Use readFileSync if you want to return something without having to use a callback.

function get(p) {
    var file = fs.readFileSync('.' + p,'utf8');
    return file ? file : "EERRRORRRRR";
}

This assumes you don't mind using synchronous/blocking code.

1 Comment

Thanks, simplest fix, although i will look into both methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.