01.node使用

  1. 安装完node后,使用path命令查看到在PATH环境变中已经包含了node的安装路径, 如:'C:\Program Files\nodejs\'
    使用"node --version"或"node -v"查看node版本
  2. 运行node程序

    • 脚本模式运行node程序
        脚本代码helloworld.js的内容如下
      console.log('Hello World');
       使用cd命令进入helloworld.js文件所在目录,使用node命令运行本程序
      node helloworld.js
       
    • 交互模式运行node程序
      在终端输入node进入交互模式
      node
      >console.log('Hello World!');
      
       按两次ctrl + c 退出交互模式

  3. 创建 Node.js 应用的示例
       server.js脚本内容如下
    var http = require('http');//请求http模块
    http.createServer(function(require,response){//用createServer函数创建对象
    	/*HTTP头部
          HTTP状态值为200,即OK
          内容类型为text/plain
    	*/
    	response.writeHead(200,{'Content-Type':'text/plain'});
    	/*
    	  发送响应数据"Hello World"
    	 */
    	response.end('Hello,how are you');
    }).listen(8888);
    
    
    /*终端打印如下信息*/
    console.log('Server running at http://127.0.0.1:8888');
     在终端中使用node命令执行
    node server.js
    Server running at http://127.0.0.1:8888/
     
  4. REPL(node终端)
    R Read,读取用户输入,解析javascript数据结构并存储在内存中
    E Eval,执行输入的数据结构
    P Print,输出结果
    L Loop,循环操作以上步骤直到用户两次按下ctrl + c退出
    • 使用node命令启动node终端
    • 输入表达式后按回车键后计算结果
    • 没有使用var定义的变量直接打印出来,使用var变量定义的变量可用console.log()打印
    • node会自动检测是否为连续表达式(连续表达式自动加三个点)
    • 下划线(_)获取表达式计算结果
    • 按两次 ctrl + c 可退出node终端

      例子如下
    > x= 10
    10
    > var y= 20
    undefined
    > x + y
    30
    > console.log('x + y =' + _);
    x + y =30
    undefined
    > do{
    ... x++;
    ... console.log("x:" + x);
    ... }while(x < 15);
    x:11
    x:12
    x:13
    x:14
    x:15
    undefined
     
    REPL命令

    • ctrl + c 退出当前终端
    • ctrl + c 按下两次退出REPL
    • ctrl + d 退出REPL
    • .exit 退出REPL
    • 向上/向下 键查看输入的历史命令
    • tab 键列出表达式命令
    • .help列出终端交互命令
    • .break 和.clear退出多行表达式
    • .save filename 保存当前的 Node REPL 会话到指定文件
    • .load filename 载入当前 Node REPL 会话的文件内容。

猜你喜欢

转载自itnotesblog.iteye.com/blog/2392782
今日推荐