初学nodejs (一):nodejs 入门

本文章是一边看着 《狼书:更了不得的Node.js》一边写的,会有本身学习中遇到的问题,也会有书中的一些知识

Hello Node.js !

最简单的例子
  • 建立 helloworld.js, 代码以下。
"use strict"
    console.log("Hello world");
  • 在终端中执行
$ node helloworld.js
    > Hello World

node 命令和 console.log函数的差异在于: console.log须要再浏览器的控制台中查看,而nodejs是直接在终端输出。javascript

Hello CommonJS

Nodejs 是基于CommonJS规范实现的,每个文件都是一个模块,每一个模块代码都要遵照CommonJS规范, 多个文件之间的调用的核心也是基于模块的对外暴露接口和互相引用。因此学习CommonJS是很必要的。下面演示下node.js中CommonJS的写法。
  • 建立两个文件夹: hello.jshello_test.js
// hello.js
    module.exports = function(){
        console.log("Hello CommonJS!");
    }
    
    // hello_test.js
    const hello = require("./hello.js");
    
    hello();
  • 执行
$ node hello_test.js
    > Hello CommonJS!

Hello HTTP

  • 新建 hello_node.js
// "hello_node.js"
    "use strict"
    const http = require('http');
    
    http.createServer((req, res)=>{
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello Node.js!');
    }).listen(3000, "127.0.0.1");
    
    console.log("Server running at http://127.0.0.1:3000/");
  • 启动服务
$ node hello_node.js
    > Server running at http://127.0.0.1:3000/
上面代码的知识点:
引用了Node.js SDK内置的名为 http的模块
经过 http.createServer建立了一个HTTP服务
经过 listen方法制定服务运行的 端口 和 IP 地址
req: 全写 request,是浏览器发送过来的请求信息。 res:全写response,是返回给浏览器请求的信息

短短的几行,咱们的HTTP的服务就跑起来了,真的是好简单啊。java

图片描述

下一篇:初学nodejs (二):用vscode断点调试咱们的代码node

相关文章
相关标签/搜索