使用node . js怎么搭建一个服务器

  介绍

这篇文章给大家介绍使用节点。js怎么搭建一个服务器,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

& # 39; use 严格# 39;   var  url =,要求(& # 39;url # 39;);   var  path =,要求(& # 39;path & # 39;);   var  fs =,要求(& # 39;fs # 39;);   var  http =,要求(& # 39;http # 39;);//get 从而,current 路径//var  root =, path.resolve(& # 39; # 39;公司);//以当前的目录为服务器的根目录   var  root =, path.resolve (process.argv[2], | |, & # 39;强生# 39;);//以输入的参数作为服务器的根目录,如果没有输入参数就将当前目录作为服务器根目录   console.log (& # 39; local  root  dir : & # 39;, +,根);//create 服务器   var  server =, http.createServer(函数(请求,响应),{//才能get 从而path  of  URL   var 才能;pathname =, url.parse (request.url) .pathname;//才能get 从而local 路径   var 才能;filepath =, path.join(根,,路径名);//才能get 从而file  stat 以及output 从而request  file  by  callback 函数   fs.stat才能(filepath,函数(呃,,统计),{   ,,,如果(! err ,,, stat.isFile ()), {   ,,,,,console.log (& # 39; 200 & # 39;, +, request.url);   ,,,,,response.writeHead (200);   ,,,,,fs.createReadStream (filepath) .pipe(响应);//没有必要手动读取文件内容。由于响应对象本身是一个Writable 流,直接用管()方法就实现了自动读取文件内容并输出到HTTP响应。   ,,,},{else    ,,,,,console.log (& # 39; 404 & # 39;, +, request.url);   ,,,,,response.writeHead (404);   ,,,,,response.end (& # 39; 404, Not 发现# 39;);   ,,,}   ,,});   });   server.listen (8080);   console.log (& # 39; Server  is  running  at  http://127.0.0.1:8080 & # 39;);

对于其中一些函数的解释:

path.resolve(),路径寻航(这名字不错)   path.resolve ([…],,)

有个解释很有趣:相当于不断地调用系统的cd指令

,

path.resolve (& # 39; foo/bar # 39;,, & # 39;/tmp/文件/& # 39;,,& # 39;. . & # 39;,,& # 39;a/. ./子文件# 39;)//相当于:   cd  foo/bar   cd //tmp/文件   cd  . .   cd /. ./subfile1   path.join ([path2],路径[2]…),路径合并

将所有名称用路径。seq串联起来,然后用normailze格式化

,

path.join (& # 39;///foo # 39;,, & # 39;酒吧# 39;,,& # 39;//巴兹/asdf # 39;,, & # 39; quux& # 39;,, & # 39; . . & # 39;);=祝辞& # 39;/foo/bar/巴兹/asdf # 39;

既然提到了正常化

那么:

格式化路径path.normalize (p)
将不符合规范的路径格式化,简化开发人员中处理各种复杂的路径判断

,

path.normalize (& # 39;/foo/bar//巴兹/asdf/quux/. . & # 39;);=祝辞,& # 39;/foo/bar/巴兹/asdf # 39;

http.response.end()结束相应,告诉客户端所有消息已经发送。当所有要返回的内容发送完毕时,该函数必须要被调用一次。如果不调用该函数,那么客户端将会永远处于等待状态。

使用方法:

response.end((数据),[编码])

数据结束()执行完毕后要输出的字符,如果指定了数据的值,那就意味着在执行完response.end()之后,会接着执行一条响应。编写(数据、编码);

编码对应的数据字符编码

关于使用node . js怎么搭建一个服务器就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。

使用node . js怎么搭建一个服务器