Node.js 模块简单用法

25次阅读

共计 704 个字符,预计需要花费 2 分钟才能阅读完成。

之前使用 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: 小明

正文完
 0