初识nodejs
nodejs需会工具
- nvm工具实现nodejs任意版本切换
- npm下载nodejs所需模块
- nrm切换npm下载源
- 学习网址推荐:https://cnodejs.org/
- 查看官方文档请到nodejs中文网:http://nodejs.cn/
入门须知
-
cmd下执行node hello.js文件可以运行js文件
-
nodejs安装后设置下载模块和代码存放路径便于统一管理
-
使用nodejs编程需了解
-
js三大组成部分:ECMASCRIPT(规范,申明js变量、判断、循环等语法)、DOM(document文档节点)、BOM(浏览器对象window、location等)
-
nodejs内置模块:http服务、fs文件操作、url路径、path路径处理、os操作系统
-
第三方模块
-
自定义模块:自己创建的js文件
-
模块概念
-
一个文件就是一个模块,通过exports和modul.exports来导出模块中的成员,通过require来加载模块
###导出模块 //写法1 exports.属性/方法名=变量名 //写法2 module.exports.属性/方法名=变量名; ###外部引用 var 对象=require('路径及文件夹名') //代码b.js //步骤定义 function add() { // body... console.log('this is add'); } function del() { // body... console.log('this is del'); } function edit() { // body... console.log('this is edit'); } function select() { // body... console.log('this is select'); } //步骤2导出 exports.add = add; exports.del = del; exports.edit = edit; exports.select = select; //代码a.js //引入自定义模块 var b = require('./b'); console.log(b); b.add(); b.del();
-
-
内置模块
-
os模块使用
//创建os对象(引入内置os模块) var os=require('os'); //调用os对象方法 console.log('hello'+os.EOL +"nodejs example"); console.log('主机名'+os.hostname()); console.log('操作系统名'+os.type()); console.log('操作系统平台'+os.platform()); console.log('内存总量'+os.totalmem+"字节"); console.log('空闲内存'+os.freemem+"字节.");
-
path模块
//引入内置模块 var path = require('path'); var testData="G:/mythempic/picture/6.png"; console.log(path.basename(testData)); testData=path.dirname(testData); console.log(testData); console.log(path.basename(testData));
-
fs模块
//引入fs内置模块,写入数据 var fs=require('fs'); //通过fs模块创建文件写入你好,nodejs fs.writeFile('./a.txt','你好,nodejs',function (err) { // body... // err为null 成功 //err不为null 有问题 if (err) { console.log(err); return; } console.log("success"); }); //引入fs模块,读取数据 var fs=require('fs'); //从a.txt读取文件内容 // fs.readFile('a.txt',function (err,data) { fs.readFile('a.txt','utf8',function (err,data) { // body... if(err){ console.log(err); return; } console.log('success'+data);//读取的内容不是我们可识别的内容 console.log('success'+data.toString()); });
-
http模块
//引入模块 var http=require('http'); //创建web服务器 var server=http.createServer(); //监听请求 server.on('request',function (req,res) { // body... console.log('收到用户请求'+req.url); //判断请求路径 if(req.url=='/'){ $msg='this is index'; }else if(req.url='/login'){ $msg='this is login'; }else{ $msg='404'; } res.setHeader('Content-Type','text/html;charset=utf-8');//解决中文乱码 //请求信息 console.log(req.headers); console.log(req.rawHeaders); console.log(req.httpVersion); console.log(req.url); //响应信息 res.statusCode=404; res.statusMessage='Not found'; res.write('hello nodejs,这是第一个请求'); res.write($msg);//根据路径展示 res.end(); }); //启动服务 server.listen(8080,function () { // body... console.log('启动成功,访问路径-localhost:8080'); });
网友评论