一:复制官网的代码,建立一个简单的服务器
const http = require(‘http‘); const hostname = ‘127.0.0.1‘; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; //返回的状态码 res.setHeader(‘Content-Type‘, ‘text/plain‘); //返回类型为纯文本 res.end(‘Hello World\n‘); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
二:了解nodejs的模块
三:创建一个简单的校园模块:
1:添加学生的模块: students.js
function add(name) { console.log(‘add student‘+ name) } exports.add = add
2:添加老师的模块: teacher.js
function add(name) { console.log(‘add teacher‘+ name) } exports.add = add
3:添加班级的模块: klass.js
// 使用模块之前需要require var student = require(‘./student‘) //将模块对象赋值给局部变量 var teacher = require(‘./teacher‘) function add(teacherName, students) { teacher.add(teacherName) students.forEach(function (item, index) { student.add(item) }) } exports.add = add
4:添加学校的模块: index.js
var klass = require(‘./klass‘) exports.add = function (klasses) { forEach(function (item, index) { var _klass = item var teacherName = item.teacherName var students = item.students klass.add(teacherName, students) }) }
时间: 2024-10-13 03:03:38