Получение 'undefined' из response.write (string) - это JS - PullRequest
0 голосов
/ 30 октября 2018

Я создаю http-сервер с JS и Node JS.

Он состоит из формы, в которую вы можете ввести текст, который должен быть путем к файлу. После того, как вы нажмете кнопку «Отправить», она должна показать на веб-странице содержимое этого файла.

Я читаю содержимое файла с помощью функции file (pathname) и возвращаю его в виде строки. Затем я пытаюсь показать содержимое на веб-странице с помощью:

response.write ('Содержимое файла:' + строка); но он показывает «Содержимое файла: не определено»

Я думаю, что моя проблема связана с response.write (), потому что когда я использую console.log (), чтобы показать, что содержимое файла работает правильно.

Что я делаю не так?

Вот код, который вы нажимаете при отправке:

if(url_parts.pathname == '/submit') { //Processing the form content, if the relative URL is '/ submit'
    var pathname=url_parts.query['name']; //Read the contents of the field (form) named 'name'
    var string = file(pathname); //file(pathname) returns the content of the file.
    console.log("Creating a response header")
    response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});  //Creating an answer header - we inform the browser that the body of the answer will be plain text
    console.log("Creating the body of the response")
    response.write('File content: '+ string); // Write content of the file
    response.end(); //The end of the response - send it to the browser
    console.log("Sending a response")
}

ВСЕ КОД:

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


function file(pathname){
    fs.stat(pathname, function(err, stats) {
    console.log("----------------------------------------------------------");
    console.log("FILE OPERATION RESULT:");
    console.log("----------------------------------------------------------");
    if (err){ console.log("'" + pathname + "' is not a directory or a file");
    } else if(stats.isDirectory()){
        console.log("Is a directory");
    } else if(stats.isFile()){
        console.log("Is a file");
        console.log("Reading content...");
        console.log("---------------");
        fs.readFile(pathname, function (err, data) {
            fileContent=data.toString('utf8');
            console.log(fileContent);
            return fileContent;
        });
    }
});
}

http.createServer(function(request, response) {

    console.log("--------------------------------------")
    console.log("The relative URL of the current request: "+request.url+"\n")
    var url_parts = url.parse(request.url,true); //parsing (relative) URL

    if(url_parts.pathname == '/submit') { //Processing the form content, if the relative URL is '/ submit'
        var pathname=url_parts.query['name']; //Read the contents of the field (form) named 'name'
        var string = file(pathname);
        console.log("Creating a response header")
        response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});  //Creating an answer header - we inform the browser that the body of the answer will be plain text
        console.log("Creating the body of the response")
        response.write('File content: '+ string); //WRITE FILECONTENT IF PATHNAME IS A FILE
        response.end(); //The end of the response - send it to the browser
        console.log("Sending a response")
    }
    else { //Generating the form
        console.log("Creating a response header")
        response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});  //Creating a repsonse header - we inform the browser that the body of the response will be HTML text
        //and now we put an HTML form in the body of the answer
            console.log("Creating a response body")
        response.write('<form method="GET" action="/submit">');
        response.write('<label for="name">Write pathname</label>');
        response.write('<input name="name">');
        response.write('<br>');
        response.write('<input type="submit">');
        response.write('<input type="reset">');
        response.write('</form>');
        response.end();  //The end of the response - send it to the browser
        console.log("Sending a response")
    } 
}).listen(8080);
console.log("The server was started on port 8080");
console.log("To end the server, press 'CTRL + C'");
...