node初体验

栏目: JavaScript · 发布时间: 6年前

内容简介:在学习webpack和vue的过程中经常会遇到关于node的知识,CommonJS规范等,所以对于前端来说学习node是非常有必要的,所以就有了这一篇node初体验的文章。这个不多说,在node官网下载安装包直接安装就可以,node预设了npm,npm是一个用javascript写的包管理器,用于管理模块,想了解更多可以到https://www.npmjs.com/上去看,上面有非常多的模块,下面直接进入正文。用node直接撸了一个处理post请求,主要的知识点有函数式编程、路由、阻塞与非阻塞、回调、事件轮

在学习webpack和vue的过程中经常会遇到关于node的知识,CommonJS规范等,所以对于前端来说学习node是非常有必要的,所以就有了这一篇node初体验的文章。

node安装

这个不多说,在node官网下载安装包直接安装就可以,node预设了npm,npm是一个用javascript写的包管理器,用于管理模块,想了解更多可以到https://www.npmjs.com/上去看,上面有非常多的模块,下面直接进入正文。

正文

用node直接撸了一个处理post请求,主要的知识点有函数式编程、路由、阻塞与非阻塞、回调、事件轮询、内部和外部模块等等。

index.js

var server = require('./server.js'),
    router = require('./router.js'),
    requestHandle = require("./requestHandlers.js"),
    handle = {};

handle['/'] = requestHandle.start;
handle['/upload'] = requestHandle.upload;
handle['/start'] = requestHandle.start;
server.start(router.route,handle);

复制代码

server.js

function start(route,handle){

    var http = require("http");
    var url = require("url");
    // 请求
    function onRequest(request,respone)
    {
        var pathname=url.parse(request.url).pathname,
            postData="";
      
        request.setEncoding('utf8');
        request.addListener('data',function(postDatachunk)
        {
            postData += postDatachunk;
        });
        request.addListener('end',function()
        {
            route(pathname,handle,respone,postData);
        });
    }

    http.createServer(onRequest).listen(8888);
    console.log("server is start");
}
//导出函数
exports.start = start;
复制代码

router.js

function route(pathname,handle,respone,postData)
{
    console.log('请求来自'+pathname);
    if(typeof(handle[pathname]) === 'function')
    {
        handle[pathname](respone,postData);
    }else{
        console.log("404 not found");
        respone.writeHead(200,{"Content-Type":"text/plain"});
        respone.write("404 not found!");
        respone.end();
    }
}

exports.route = route;
复制代码

requestHandlers.js

var querystring = require('querystring');
function upload(respone,postData)
{
    console.log("这个是upload路由");
    respone.writeHead(200,{"Content-Type":"text/plain"});
    respone.write(querystring.parse(postData).txt);
    respone.end();
};
function start(respone)
{
    console.log("这个是start路由");
    var body =  '<html>'+
                '<head>'+
                '<meta charset="UTF-8">'+
                '<style>'+
                '#txt{float:left;width: 250px;height: 50px;border-right:none;border-top-left-radius: 3px;border-bottom-left:3px;}'+
                '#submit{float:left;border-sizing:border-box;width: 100px;height: 50px;background:skyblue;color: #fff;font-size: 18px;}'+
                '</style>'+
                '</head>'+
                '<body>'+
                '<form action="/upload" method="post">'+
                '<input type="text" id="txt" name="txt" />'+
                '<input type="submit" value="提交" id="submit" name="submit"/>'+
                '</form>'+
                '</body>'+
                '</html>';
    respone.writeHead(200,{"Content-Type":"text/html"});
    respone.write(body);
    respone.end();
};

exports.upload = upload;
exports.start = start;
复制代码

总结

事件轮询(event loop)

JavaScript是一门单线程语言,也就是说如果遇到大量的任务或者耗时任务,线程就会被堵塞,需要等待其执行完毕,这就会造成页面假死等状态,为了解决这个问题,就需要有eventloop线程,简单来说我们可以新建一个eventloop线程负责主线程与其它进程的通信,这样在有大量任务和耗时任务时我们就交给eventloop线程去处理,一般是各种io操作,处理完毕后返回给主线程并执行预先设置的回调函数,这个模式我们就叫做非阻塞模式或者异步模式。 在这次node初体验中,我使用了child_process模块来实现了一个非阻塞操作 代码如下

var exex = require("child_process").exec;
function test(respone)
{
    exec("find /",{ timeout : 10000, maxBuffer : 200*1024},function(error,stdout,stderr)
    {
        respone.writeHead(200,{"Content-Type":"text/plain"});
        respone.write(stdout);
        respone.end();
    });
    // 阻塞操作
    // var time = new Date().getTime();
    // while(new Date().getTime()<time + 30000);
    // console.log("xxxxxxxxxxxxxxxxxxxxxxxxxx");
}
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Git (Second Edition)

Pro Git (Second Edition)

Scott Chacon、Ben Straub / Apress / 2014-11-9 / USD 59.99

Scott Chacon is a cofounder and the CIO of GitHub and is also the maintainer of the Git homepage ( git-scm.com ) . Scott has presented at dozens of conferences around the world on Git, GitHub and the ......一起来看看 《Pro Git (Second Edition)》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具