Node.js简述

Node.js是2009年5月由Ryan Dahl 发布的服务器程序。html

它封装了Google V8 JavaScript 引擎, 并将其重建为可在服务器上使用。node

它旨在提供一种简单的构建可伸缩网络程序的方法。它更改了一向的链接服务器的方法(好比一个请求就会成生一个新的OS线程,并分配必定量的RAM)。每个链接只是发射一个在node引擎的进程中运行的事件,采用事件驱动,这样就解决了高并发。一个链接被创建,这是一个事件。数据经过链接进行接收,这也是一个事件。数据经过链接中止,这仍是一个事件。因此Node对于处理高流量程序很理想。web

Node.js用的common.js架构,采用CMD模式。npm

npm是Node.js的包管理工具。服务器

实战一下,搭建Web服务器网络

 在网站根目录添加server.js, 添加如下代码架构

// http协议模块
var http = require('http');
// url解析模块
var url = require('url');
// 文件系统模块
var fs = require('fs');
// 路径解析模块
var path = require('path');
var server = http.createServer(function(request,response){
   var hasExt = true;
    var requestUrl = request.url;
    var pathName = url.parse(requestUrl).pathname;
 
    // 对请求的路径进行解码,防止中文乱码
    pathName = decodeURI(pathName);
 
    // 若是路径中没有扩展名
    if (path.extname(pathName) === '') {
        // 若是不是以/结尾的,加/并做301重定向
        if (pathName.charAt(pathName.length-1) != '/'){
            pathName += '/';
            var redirect = 'http://' + request.headers.host + pathName;
            response.writeHead(301, {
                location: redirect
            });
            response.end();
            return ;
        }
        // 添加默认的访问页面,但这个页面不必定存在,后面会处理
        pathName += 'index.html';
        hasExt = false; // 标记默认页面是程序自动添加的
    }
 
    // 获取资源文件的相对路径(相对于这个js文件的地址)
    var filePath = path.join('path', pathName);
 
    // 获取对应文件的文档类型
    var contentType = this.getContentType(filePath);
 
    // 若是文件名存在
    fs.exists(filePath, function(exists) {
        if (exists) {
            response.writeHead(200, {'content-type': contentType});
            var stream = fs.createReadStream(filePath, {flags: 'r', encoding: null});
            stream.on('error', function () {
                response.writeHead(500, {'content-type': 'text/html'});
                response.end('<h1>500 Server Error</h1>');
            });
            // 返回文件内容
            stream.pipe(response);
        } else { // 文件名不存在的状况
            if (hasExt) {
                // 若是这个文件不是程序自动添加的,直接返回404
                response.writeHead(404, {'content-type': 'text/html'});
                response.end('<h1>404 Not Found</h1>');
            } else {
                // 若是文件是程序自动添加的且不存在,则表示用户但愿访问的是该目录下的文件列表
                var html = "<head><meta charset='utf-8'></head>";
                try {
                    // 用户访问目录
                    var filedir = filePath.substring(0, filePath.lastIndexOf('\\'));
                    // 获取用户访问路径下的文件列表
                    var files = fs.readdirSync(filedir);
                    // 将访问路径下的因此文件一一列举出来,并添加超连接,以便用户进一步访问
                    for (var i in files) {
                        var filename = files[i];
                        html += "<div><a  href='" + filename + "'>" + filename + "</a></div>";
                    }
                } catch (e){
                    html += '<h1>您访问的目录不存在</h1>';
                }
                response.writeHead(200, {'content-type': 'text/html'});
                response.end(html);
            }
        }
    });
});
 server.listen(3030);


 

执行node server.js, 启动web服务器并发

访问http://localhost:3030ide

停止服务器用ctrl+c, 或者调用server.close();高并发

Node语法可参考:https://juejin.im/post/5c4c0ee8f265da61117aa527

 

相对路径:

./表示当前路径下。../表示上一级路径 

做者:

After working on the Node project since 2009, Dahl announced in January, 2012 that he would step away from the project and turn over the reins to NPM creator and then Joyent employee Isaac Z. Schlueter.

Ryan Dahl gave the following reason for moving on from the project:

“After three years of working on Node, this frees me up to work on research projects. I am still an employee at Joyent and will advise from the sidelines but I won’t be involved in the day-to-day bug fixes.”

相关文章
相关标签/搜索