zoukankan      html  css  js  c++  java
  • Node.js入门(一)

    一、Node.js环境配置:

    http://www.w3cschool.cc/nodejs/nodejs-install-setup.html

    二、命令行控制(cmd/命令提示符):

    1.读取文件方式:

    C:UserUserName>

    C:UserUserName>E:  //你的node项目文件夹所在的磁盘

    E:>cd ode  //我的node文件都放在node文件夹下

    E:>node>node server.js

    2.交互模式:

    C:UserUserName>

    C:UserUserName>E:  

    E:>cd ode

    E:>node>node

    >console.log('Hello World!');

    Hello World!

    undefined

    三、Node.js创建HTTP服务器

    1.在你的项目的根目录下创建一个叫 server.js 的文件,并写入以下代码:

    1 var http = require('http'); //请求Node.js自带的http模块
    2 
    3 http.createServer(function (request,response){  //createServer()是http模块自带的方法,这个方法会返回一个对象,此对象的listen()方法,传入这个 HTTP 服务器监听的端口号。
    4   response.writeHead(200,{'Content-Type':'text/plain'});
    5   response.end('Hello World
    ');
    6 }).listen(8888);
    7 
    8 console.log('Server running at http://127.0.0.1:8888/');

    这样就完成了一个可以工作的 HTTP 服务器。

    2.使用 node命令 执行以上的代码:

    E:>node>node server.js

    Server running at http://127.0.0.1:8888/

    3.接下来,打开浏览器访问 http://127.0.0.1:8888/,你会看到一个写着 "Hello World"的网页。

    四、Node.js模块

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

    1.创建一个 'main.js' 文件,代码如下:

    1 var hello = require('./hello');  //引入了当前目录下的hello.js文件(./ 为当前目录,node.js默认后缀为js)。
    2 
    3 hello.world();

    2.创建一个 'hello.js'文件,此文件就是hello模版文件,代码如下:

    1 exports.world = function (){  //exports 是模块公开的接口
    2   console.log('Hello world');
    3 };

    3.把对象封装到模块中:

    1 module.exports = function (){
    2 
    3   // . . .
    4 
    5 };

    例如:

     1 //hello.js 
     2 function Hello() { 
     3     var name; 
     4     this.setName = function (thyName) { 
     5         name = thyName; 
     6     }; 
     7     this.sayHello = function (){ 
     8         console.log('Hello ' + name); 
     9     }; 
    10 }; 
    11 module.exports = Hello;

    这样就可以直接获得这个对象了:

    1 //main.js 
    2 var Hello = require('./hello'); 
    3 hello = new Hello(); 
    4 hello.setName('BYVoid'); 
    5 hello.sayHello();
     
  • 相关阅读:
    Linux 常用指令【持续更新】
    我的 MyBatis 实现的 Dao 层
    Mybatis 点点滴滴
    Redis 初识
    Mybatis 映射关系
    Mybatis 类属性和字段映射小小分析
    Mybatis 中 sql 语句的占位符 #{} 和 ${}
    使用 Maven 管理项目
    Maven 项目依赖 pom 文件模板
    Maven 私服安装和启动
  • 原文地址:https://www.cnblogs.com/liuqiuchen/p/4515788.html
Copyright © 2011-2022 走看看