您的位置:首页 > Web前端 > Node.js

Node.js入门第二讲

2015-12-15 22:29 429 查看
Node.js第二讲

  2.1)Hello World

  打开一个文本编辑器,在其中输入:

  console.log("Hello World");

  并保存为helloworld.js,打开dos窗口进入该文件的目录运行 

  node helleworld.js,执行则可以看到输出的HelloWorld.

  2.2)Node.js命令行工具

    node -v 查看版本号

    node -e eval script 

       eval函数解析一个js代码,把一个字符串解析成一个js代码,然后直接执行。

    例如:

    node -e ("console.log('hello')");

    node 直接进入编译模式

    22   -->  22

    “44tt”   -->44tt

    console.log('111');  -->111

    第一行是输入,第二行是输出

  2.3)建立HTTP服务器

  在node.js中,不会使用Apache服务器,因为它内部使用的是V8引擎作为它的服务器,然后解析js文件,同时它集成了一套HTTP的服务器,它会提供很多模块和包供我们使用.

  通过require()引入一个HTTP的包,然后就拿到了这个包的一个http对象,通过调用该对象的createServer()方法实现HTTP服务器的创建,方法里会有一个对回调函数的使用

  创建一个app.js:

  var http = require('http');

  http.createServer(function(req,resp){

  resp.writeHead(200,{"Content-Type":"text/html"});

  resp.write("<h1>Hello Node.js</h1>");

  resp.end("end");

  }).listen(3000);

  console.log("Http server is listening at port 3000");

     接下来node app.js,打开浏览器访问http://localhost:3000即可。这样就部署了一个web。比tomcat,resin更加方便。

  2.4)调试代码

    安装supervisor来控制调试代码,不需要每次停止重启node.js的服务

    npm install -supervisor -g

    使用supervisor app.js启动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息