Node.js 模块简单用法

之前使用node的包管理器npm,生成vue-cli工程模板,而且经常通过npm进行包管理,为了更好的了解nodejs包管理,学习一下nodejs
一、使用Nodejs搭建一个web服务器
默认大家已经安装好了node,直接写项目
1.1、创建文件夹 scott > imooc > begining          创建文件 server.js
var http = require(‘http’)

var server = http.createServer(function (req, res) {
res.writeHead(200,{‘Content-Type’:’text/plain’})
res.end(‘Hello Nodejs \n’)
})
server.listen(1337, ‘127.0.0.1’)

1.2、运行文件
//cmd cd 当前目录中
scott\imooc\begining> node server

1.3、打开浏览器输入 127.0.0.1:1337         页面显示 Hello Nodejs
二、简单的node模块
创建模块、导出模块、加载模块、使用模块
2.1、创建模块 school > student.js
// 编写方法
function add (stu) {
console.log(‘New student:’ + stu)
}
// 导出模块
exports.add = add
2.2、创建文件 school > stuInfo.js
// 加载模块
var stu = require(‘./stu’)

// 使用模块
stu.add(‘小明’)
2.3、运行文件,运行方法,显示信息
// cmd 当前路径,执行命令
school>node stuInfo
New student:小明

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理