簡體   English   中英

盡管顯式return語句,Node.JS返回未定義

[英]Node.JS returning undefined, despite explicit return statement

我有這段簡單的代碼:

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

當我運行並連接到服務器時,它會記錄未定義的信息...

當我添加“ console.log(cont)”時,例如:

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

; 它記錄正確的內容,那么為什么函數返回未定義? 內容存在...

我該如何解決這個問題?

如果您不知道,代碼的原始上下文是一個簡單的Web服務器。

閱讀有關回調和異步函數的信息,您可以在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

node.js中的readFile是異步的(以及幾乎所有其他功能)。 您不能從異步函數返回值,而是需要使用一個在操作結束后將被調用的回調函數:

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

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

如果要返回某些內容而不必使用回調,請使用readFileSync

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

假設您不介意使用同步/阻塞代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM