这段代码中的客户端、路径和数据是什么?

What is client, path and data in this code?

本文关键字:路径 数据 是什么 客户端 段代码 代码      更新时间:2023-09-26

我正在学习Node.js我已经创建了服务器和客户端.js文件,但我不明白一些事情。例如,在webserver.js文件中,我不知道pathname的用途是什么。同样,在client.js文件中,datapath是什么?

如果你认为我应该阅读它的基础知识,请提供给我一个有用的链接,如果你可以。我试着去找,但是没有找到。

webserver.js

var fs=require('fs');
var url=require('url');
var http=require('http');
http.createServer(function(request, response){
    var pathname=url.parse(request.url).pathname;
    console.log("Pathname: "+pathname+"Request.url: "+request.url);
    fs.readFile(pathname.substr(1), function(err, data){
        if(err){
            console.log("Error reading.");
            response.writeHead(400, {'content-type' : 'text/html'});
        }else{
            response.writeHead(200, {'content-type' : 'text/html'});
            response.write(data.toString());
        }
        response.end();
    });
}).listen(8081);
console.log("Server is running.");

client.js

var http=require('http');
var options={
    host: 'localhost',
    port: '8081',
    path: '/index.html'
};
var callback=function(response){
    var body='';
    response.on('data', function(data){
        body+=data;
    });
    response.on('end', function(){
        console.log("Data received.");
    });
}
var req=http.request(options, callback);
req.end();

原始代码源代码在这里:code

pathname是URL的路径部分,位于主机之后和查询之前,如果存在,包括初始斜杠。

pathname是请求到http服务器的路径。这个问题的示例路径名是/questions/40276802/what-is-client-path-and-data-in-this-code。client.js中的path也是一样的。

你可以在Node.js文档中找到解析URL为路径名的文档:https://nodejs.org/api/http.html#http_message_url

Node的HTTP客户端使用流,它发出几个事件。data是用缓冲区调用的,通常将缓冲区添加到数组中,然后再进行concat(正如代码所做的那样)。end在发送所有缓冲区时被调用。

你可以从Node.js文档中找到处理事件的文档:https://nodejs.org/api/stream.html#stream_class_stream_readable

pathname是请求的路径。您应该查看url包的文档:npm-url

在您的client.js中:data是来自服务器的响应数据。再次检查http文档:HTTP|Node.js

关于学习回调和Node.js的所有内容:nodesschool .io