Node.js学习笔记2

在优酷上学了《从0到1实现一个NodeJS框架》

第一集,虽然代码简单,但蕴含的知识一点也不少,特此摘记温故

知识点:定义模块

/SERVER/server_modules/server.js  定义了本次核心模块

const http = require('http')  //引用nodeJS原生JS
const {serverPort} = require('../config') //引用我们自定义模块

const server = ()=>
    //创建一个http服务器,传递给createServer一个回调函数,这个函数接受2个参数
    http.createServer((req,res) =>{
        res.writeHead(200,{'Content-type': 'text/html'});
        res.end('Hello World')
    }).listen(serverPort, ()=>{
    console.log('server start') //如果执行成功了打印一串文字
    }) //监听一个端口 

module.exports = server; //把这个模块暴露出去

知识点

1).nodeJS初始化项目命令, npm init
2).新建 config.js 配置文件,使用 const 定义常量,如

const config = {
    serverProt : 3000
} 

3). 把模块给暴露给外部,如
module.exports = config; //这样其它模块就可以访问改模块了

4). const http = require(‘http’) //nodeJS原生模块

5). 启动Portal(运行模块),涉及在 package.json 中“scripts”属性中的定义相关指令,如 “start” :“node ./app.js”

猜你喜欢

转载自www.cnblogs.com/zhuji/p/12466384.html
今日推荐