Node笔记(1)
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
进程
1.process.argv 用于获取当前进程信息
0--node.exe的目录
1--js文件的目录
2--第一个参数process.argv.slice(2) 获取从第一个参数开始的参数
2.process.env 获取当前系统的环境变量- 3.process.stdout.write('xxx')
- console.log('xxx') = process.stdout.write('xxx\n');
- 4.process.stdin.on('data',function(data){
- process.stdout.write(data);
})
//回车时触发
- 传统的java,.net遇到阻塞io时会创建新的线程来处理。 node内部实现其实也是多线程的,(通过线程池)
//
多线程都是‘假’的,对于一个cpu核心。创建线程需要时间,线程数量有限,cpu在不同线程间切换需要转换上下文,耗费时间
多线程的意义并不大(多核心cpu则可能会提升效率)- node的主线程————事件队列与事件循环圈。
模块
exports的实现:
module是定义在.js文件中的对象
xxx.js
console.log(module)
....(打印出module对象)
module中有一个exports对象,可以向内添加属性和方法
(参考 https://www.cnblogs.com/wbxjiayou/p/5767632.html)
写一个require的实现:
function $require(id){
const fs = require('fs');
const path = require('path');
const filename = path.join(__dirname,id);
$require.cache = $require.cache || {};
if($require.cache[filename]){
return $require.cache[filename].exports;
}
const dirname = path.dirname(filename);
let code = fs.readFileSync(filename,'utf8');
let module = { id:filename,exports:{} };
let exports = module.exports;
code=`
(function($require,module,exports,__dirname,__filename){
${code}
})($require,module,exports,dirname,filename)
;`;
eval(code);
$require.cache[filename] = module;
return module.exports;
}
var m4 = $require('../xx.js');
m4.say();
...
清空require中的缓存机制:
Object.keys(require.cache).forEach((key)=>{delete require.cache[key]});
内置模块:
path:处理文件路径。
fs:操作(CRUD)文件系统。
child_process:新建子线程。
util:提供一系列实用小工具。
http:提供http服务器功能。
url:用于解析URL。
querystring:解析URL中的查询字符串。
crypto:提供加密和解密功能。
..
包(Node package manager):
Buffer
:读取文件时没有指定编码默认读取的是一个Buffer(缓冲区)
缓冲区:内存中操作数据的容器。
为什么要有缓冲区?
早期JS擅长处理字符串,及HTML文档,不会接触到二进制的数据。
而在Node中操作数据,网络通信是完全没法以字符串的方式操作的,所以在Node中引入了一个二进制缓冲区的实现,Buffer
//readfile的方式确实是使用buffer,但是也是一次性读取
Stream:
读一点数据,处理一点点数据(读到有限长的buffer中,然后再读取出来,)
写一个歌词滚动效果的实现:
假定有一个xxx.lrc文件
方法1.用buffer的方式读入fs.readFile(pathxx,callback)
在回调函数中对buffer进行tostring转换,然后split掉'\n',对于数组中的每一行,用正则提取时间,然后settimeout按时间显示出来
(由于对每一行处理需要耗费几毫秒的时间,可以设置begin=new Date().getTime() 然后在后面的settimeout中设置新的new Date.getTime()-begin 减掉这个时间)
方法2.用stream的方式读入 var streamReader = fs.createReadStream(filename);
var data = '';
streamReader.on('data',function(chunk){ data+=chunk.tostring(); });
streamReader.on('end',function(){console.log(data); };
在这里对data进行处理
方法3.使用readline模块,用stream的方式读入 var streamReader = fs.createReadStream(filename);
var rl = readline.createInterface({ input:streamReader });
var begin = new Date().getTime();
rl.on('line',(line)=>{....对line进行处理})
写文件
默认写入是覆盖 ,可以使用append追加
方法1.fs.writeFile(path,callback);
方法2.var streamwriter = fs.createWriteStream(path);
streamwriter.write('xxx',callback) (以流的方式写入,防止在内存中读取过多)
其他文件api
检查文件、删除、重命名..
写一个目录树显示的实现:
思路:通过使用fs.readdirSync
网络框架
Express框架的核心是对http模块的再包装
var http = require("http");
var app = http.createServer(function(request, response) {response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello world!");
});
app.listen(3000, "localhost");
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello world!');
});
app.listen(3000);
中间件(middleware)是处理HTTP请求的函数。
app.use("/home", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
});
app.use("/about", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
});
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});
http.createServer(app).listen(1337);
还可以这样写(*是指所有的请求都要先通过这个中间件)
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
});app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
});app.get("*", function(request, response) {
response.end("404!");
});
Node笔记(1)的更多相关文章
- node笔记——gulp修改静态文件的名字
cmd小技巧: 1.换到下级或同等级目录 D: 2.换到上级目录 cd.. node 包管理器小技巧[以gulp为例] npm install --save-dev gulp gulp-concat ...
- Node笔记五-进程、线程
进程 -每一个正在运行的应用程序都称之为进程 -每一个应用程序都至少有一个进程 -进程是用来给应用程序提供一个运行的环境 -进程是操作系统为应用程序分配资源的一个单位线程 -用来执行应用程序中的代码 ...
- Node笔记四
异步操作 -Node采用chrome v8 引擎处理javascript脚本 --v8最大特点就是单线程运行,一次只能运行一个任务 -Node大量采用异步操作 --任务不是马上执行,而是插在任务队列的 ...
- Node笔记三
global --类似与客户端javascript运行环境中的window process --用于获取当前node进程信息,一般用于获取环境变量之类的信息 console --node中内置的con ...
- Node笔记二
### 安装包的方式安装 - 安装包下载链接: + Mac OSX: [darwin](http://npm.taobao.org/mirrors/node/v5.7.0/node-v5.7.0.pk ...
- Node笔记一
什么是javascript? --脚本语言 --运行在浏览器中 --一般用来做客户端页面的交互 javascript运行环境 --运行在浏览器内核中的JS引擎 浏览器这种javascript可以做什么 ...
- node笔记
基础入门可参考: <一起学 Node.js>—— https://github.com/nswbmw/N-blog 核心模块使用前需要引入 let fs=require('fs'); ...
- node笔记汇总
项目依赖分两种,一个就是普通的项目依赖比如bootstrap,还用一种只是开发阶段需要用的,这种属于开发依赖比如gulp,开发依赖最终记录在devDependencies节点里面 - ...
- Node笔记 - process.cwd() 和 __dirname 的区别
process.cwd() 返回工作目录 __dirname 返回脚本所在的目录位置 单看概念觉得都差不多,有种似懂非懂的感觉,那么接下用一个简单易懂的例子来理解下这两者的区别,在此之前先看一个方法 ...
随机推荐
- poj 1734 floyd求最小环,可得到环上的每个点
#include<stdio.h> #include<string.h> #define inf 100000000 #define N 110 #define min(a, ...
- [Cypress] Find and Test Focused Input with Chrome’s DevTools in Cypress
In this lesson, we’ll add tests that finds a focused input. We’ll use Chrome’s dev tools from inside ...
- C#替换字符串起始/结尾指定的字符串
#region 替换字符串起始位置(开头)中指定的字符串 /// <summary> /// 替换字符串起始位置(开头)中指定的字符串 /// </summary> /// & ...
- leetcode解题文件夹
点击打开链接点击打开链接点击打开链接參考文献:http://blog.csdn.net/lanxu_yy/article/details/17848219 只是本文准备用超链接的方式连接到对应解答页面 ...
- Android实战简易教程-第六十六枪(server端搭建和server端Json数据交互)
学习Android有一段时间了.对server端有非常深的好奇,决定对server端的实现进行一些研究,这里实现了一个简单的小样例,用于获取server端的json数据,样例非常easy,适合刚開始学 ...
- ORACLE 按表字段值的不同统计数量
select p.id comperitorId,p.compcorp competitorName, sum(case when c.kindname = 'ATM' then c.num else ...
- CSU 1506 Problem D: Double Shortest Paths(最小费用最大流)
题意:2个人从1走到n,假设一条路第一次走则是价值di,假设第二次还走这条路则须要价值di+ai,要你输出2个人到达终点的最小价值! 太水了!一条边建2次就OK了.第一次价值为di,第二次为ai+di ...
- Java缓存server调优
搜索降级方案中xmn開始使用bizer默认的128M,很慢. 偶然改成1G,效果立刻上来,可是xmx调大并没有明显效果. 100并发 200并 ...
- androidstudio集成ijkplayer教程
介绍 ijkplayer是一款非常火的开源视频播放器,android和IOS通用.关于怎么编译怎么导入android Studio中自己的项目,其中坑很多,本篇记录下自己的操作记录.ijkplay ...
- reportlab使用示例:文字和图片
Python的reportlab专门将数据使用生成PDF中的图形和文档功能, 下载ReportLab https://pypi.python.org/simple/reportlab/ http:// ...