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

发布时间:2021-03-30 17:08:14 作者:Leah
来源:亿速云 阅读:145

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

'use strict'
var url = require('url');
var path = require('path');
var fs = require('fs');
var http = require('http');
//get the current path
//var root = path.resolve('.');//以当前的目录为服务器的根目录
var root = path.resolve(process.argv[2] || '.');//以输入的参数作为服务器的根目录,如果没有输入参数就将当前目录作为服务器根目录
console.log('local root dir :' + root);
//create server
var server = http.createServer(function(request, response) {
  //get the path of URL
  var pathname = url.parse(request.url).pathname;
  //get the local path
  var filepath = path.join(root, pathname);
  //get the file stat and output the request file by callback function
  fs.stat(filepath, function(err, stat) {
    if(!err && stat.isFile()) {
      console.log('200' + request.url);
      response.writeHead(200);
      fs.createReadStream(filepath).pipe(response);//没有必要手动读取文件内容。由于response对象本身是一个Writable Stream,直接用pipe()方法就实现了自动读取文件内容并输出到HTTP响应。
    } else {
      console.log('404' + request.url);
      response.writeHead(404);
      response.end('404 Not Found');
    }
  });
});
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');

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

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

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

eg:

path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
//相当于:
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile1
path.join([path2],path[2]...) 路径合并

将所有名称用path.seq串联起来,然后用normailze格式化

eg:

path.join('///foo', 'bar', '//baz/asdf', 'quux', '..');
=>'/foo/bar/baz/asdf'

既然提到了normalize

那么:

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

eg:

path.normalize('/foo/bar//baz/asdf/quux/..');
=> '/foo/bar/baz/asdf'

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

使用方法:

response.end([data], [encoding])

data end()执行完毕后要输出的字符,如果指定了 data 的值,那就意味着在执行完 response.end() 之后,会接着执行一条 response.write(data , encoding);

encoding 对应data的字符编码

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

推荐阅读:
  1. 使用node.js怎么搭建一个即时响应服务器
  2. 使用node.js怎么快速的搭建一个HTTP服务器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nodejs 服务器

上一篇:如何在docker中使用create命令

下一篇:怎么在PHP使用xpath解析XML

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》