zoukankan      html  css  js  c++  java
  • node.js 运行机制与简单使用

    一、hello world

      1、引入 required 模块

      2、创建服务器

      3、接收请求与响应请求

    var http = require('http');    // 载入http模块
    http.createServer(function (request, response) {
    
        // 发送 HTTP 头部 
        // HTTP 状态值: 200 : OK
        // 内容类型: text/plain
        response.writeHead(200, {'Content-Type': 'text/plain'});
    
        // 发送响应数据 "Hello World"
        response.end('Hello World
    ');
    }).listen(8888);    // 监听8888端口
    
    // 终端打印如下信息
    console.log('Server running at http://127.0.0.1:8888/');

      打开浏览器访问 http://127.0.0.1:8888/,触发响应

    二、运行机制

      Node.js 是单进程单线程应用程序,但通过事件和回调支持并发。

      我们可以通过引入 events 模块,并通过实例化 EventEmitter 类来绑定和监听事件

    // 引入 events 模块
    var events = require('events');
    
    // 创建 eventEmitter 对象
    var eventEmitter = new events.EventEmitter();
    
    // 创建事件处理程序
    var connectHandler = function connected() {
       console.log('连接成功。');
    }
    
    // 绑定 connection 事件处理程序
    eventEmitter.on('connection', connectHandler);
    
    // 触发 connection 事件 
    eventEmitter.emit('connection');

    三、模块系统

      模块是Node.js 应用程序的基本组成部分,文件和模块是一一对应的。换言之,一个 Node.js 文件就是一个模块。

      Node.js 提供了 exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口。

      1、创建模块(hello.js)

    exports.world = function() {
      console.log('Hello World');
    }

      2、使用模块(main.js)

    var hello = require('./hello');
    hello.world();

    四、全局对象

      在浏览器 JavaScript 中,通常 window 是全局对象, 而 Node.js 中的全局对象是 global,所有全局变量(除了 global 本身以外)都是 global 对象的属性。

      __filename  当前正在执行的脚本的文件名

      __dirname  当前执行脚本所在的目录

      setTimeout(cb, ms)

      clearTimeout(t)

      setInterval(cb, ms) 

      console  控制台

      process  Node.js 进程管理对象,提供了一个与操作系统的简单接口

    // 输出当前目录
    console.log('当前目录: ' + process.cwd());
    
    // 输出当前版本
    console.log('当前版本: ' + process.version);
    
    // 输出内存使用情况
    console.log(process.memoryUsage());

    参考:菜鸟教程

  • 相关阅读:
    Vsftpd 3.0.2 正式版发布
    Putdb WebBuilder 6.5 正式版本发布
    SoaBox 1.1.6 GA 发布,SOA 模拟环境
    pynag 0.4.6 发布,Nagios配置和插件管理
    Percona Playback 0.4,MySQL 负荷回放工具
    xombrero 1.3.1 发布,微型 Web 浏览器
    Hypertable 0.9.6.4 发布,分布式数据库
    libmemcached 1.0.11 发布
    CryptoHeaven 3.7 发布,安全邮件解决方案
    Android Activity生命周期
  • 原文地址:https://www.cnblogs.com/MattCheng/p/8508816.html
Copyright © 2011-2022 走看看