Readline

作者: LaLaLaLaAAA | 来源:发表于2016-08-11 09:16 被阅读0次

    Readline是Node.js里实现标准输入输出的封装好的模块,通过这个模块我们可以以逐行的方式读取数据流。使用require(“readline”)可以引用模块.

    如何使用Readline

    以使用为角度的话,学习Readline,我们需要学习它的三个部分:

    创建Readline实例

    接口方法

    监听与处理事件

    1.从键盘获取数据readline

    var readline = require('readline');
    var rl=readline.createInterface(process.stdin,process.stdout);rl.setPrompt('请输入:');
    rl.prompt();rl.on('line',(line) =>
    { var str = line.trim(); console.log('你输入的是:'+str); rl.prompt();});

    退出操作

    rl.on('line',(line) =>{ var str = line.trim(); console.log('你输入的是:'+str);
    rl.prompt();}).on('close',() =>{console.log("欢迎下次再来!");
    process.exit(); //退出进程});

    模块的定义与调用

    //创建一个文件hello.js
    exports.shangke = function(str){
    console.log('这个是上课的模块' + str);}
    //模块中函数定义和引用
    function hello(){console.log('this is hello function');}
    exports.h = hello();
    //模块调用
    var sk = require('./hello'); //在程序文件中引用刚申明的模块,注意hello模块的路径
    sk.shangke('shangke'); //使用shangke这个函数
    sk.h;//使用hello这个函数

    QueryString模块

    //可以将表单提交的数据转换成json字符串
    querystring.parse('foo=bar&baz=qux&baz=quux&corge')
    //returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
    //可以将json串转换为表单提交的数据格式
    querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })

    相关文章

      网友评论

          本文标题:Readline

          本文链接:https://www.haomeiwen.com/subject/xkojsttx.html