BEM mixin

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// Block Element
/// @access public
/// @param {String} $element - Element's name
@mixin element($element) {
&__#{$element} {
@content;
}
}

/// Block Modifier
/// @access public
/// @param {String} $modifier - Modifier's name
@mixin modifier($modifier) {
&--#{$modifier} {
@content;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.block {
/* CSS declarations for `.block` */

@include element('element') {
/* CSS declarations for `.block__element` */
}

@include modifier('modifier') {
/* CSS declarations for `.block--modifier` */

@include element('element') {
/* CSS declarations for `.block--modifier__element` */
}
}
}

类型检测

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
////
// A collection of function for advanced type checking
// @author Hugo Giraudel
////

@function is-number($value) {
@return type-of($value) == 'number';
}

@function is-time($value) {
@return is-number($value) and index('ms' 's', unit($value)) != null;
}

@function is-duration($value) {
@return is-time($value);
}

@function is-angle($value) {
@return is-number($value) and index('deg' 'rad' 'grad' 'turn', unit($value)) != null;
}

@function is-frequency($value) {
@return is-number($value) and index('Hz' 'kHz', unit($value)) != null;
}

@function is-integer($value) {
@return is-number($value) and round($value) == $value;
}

@function is-relative-length($value) {
@return is-number($value) and index('em' 'ex' 'ch' 'rem' 'vw' 'vh' 'vmin' 'vmax', unit($value)) != null;
}

@function is-absolute-length($value) {
@return is-number($value) and index('cm' 'mm' 'in' 'px' 'pt' 'pc', unit($value)) != null;
}

@function is-percentage($value) {
@return is-number($value) and unit($value) == '%';
}

@function is-length($value) {
@return is-relative-length($value) or is-absolute-length($value);
}

@function is-resolution($value) {
@return is-number($value) and index('dpi' 'dpcm' 'dppx', unit($value)) != null;
}

@function is-position($value) {
@return is-length($value) or is-percentage($value) or index('top' 'right' 'bottom' 'left' 'center', $value) != null;
}

遍历文件夹

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

var base = path.join(__dirname, "code");
var exclude = /.git*|node_modules/;
var travel = function(filePath) {
  fs.readdirSync(filePath).forEach(function(file) {
    var file = path.join(filePath, file);
    if(exclude.test(file)) return;
    if(fs.statSync(file).isDirectory()) {
      travel(file);
    } else {
      console.log(file);
    }
  });
};
travel(base);

发送邮件

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'barret.china@gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: '小胡子哥<barret.china@gmail.com>',
to: '小胡子哥<barret.china@gmail.com>',
subject: 'Snippet到来,赶紧迎接~',
text: textContent,
html: htmlConent
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});

nodejs请求并保存图片

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net
最直接的方式是:

1
2
request('http://google.com/doodle.png')
.pipe(fs.createWriteStream('doodle.png'));

但是有的时候需要异步获取,所以需要用其他方式处理:

1
2
3
4
5
6
7
8
9
10
new Promise(function(resolve, reject){
request({
url: 'http://barretlee.com/avatar.png',
encoding: 'binary'
}, function(err, res, body) {
resolve(body);
});
}).then(function(body){
fs.writeFileSync('avatar.png', body, 'binary');
})

具有 ejs layout 的 express generator

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
// app.js
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var app = express();
var path = require('path');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// 必须放在 static 设置的后面
app.use(expressLayouts);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta lang="zh">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="renderer" content="webkit">
<meta name="description" content="">
<meta name="keyword" content="">
<title>DEMO</title>
<link rel="stylesheet" href="/main.css">
</head>
<body>
<%- body %>
<script src="/main.js"></script>
</body>
</html>

nodejs多进程爬虫,榨干CPU

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
var cheerio = require('cheerio');
var request = require('request');
var cluster = require('cluster');
var mkdirp = require('mkdirp');
var path = require('path');
var fs = require('fs');

var numCPUs = require('os').cpus().length;
var baseURL = {YOUR_SPIDER_URL};
var catesQueue = [];
var subCateQueue = [];

function run (cates){

if(cluster.isMaster) {
Object.keys(cates).forEach(function(cate){
Object.keys(cates[cate]).forEach(function(subCate){
catesQueue.push({
dir: path.join('./pool', cate, subCate),
url: cates[cate][subCate],
type: "list"
});
});
});

while(numCPUs--) {
var c = cluster.fork();
if(catesQueue.length) {
c.send(catesQueue.shift());
c.on("message", function(msg){
if(typeof msg === "object") {
if(msg.type == "list") {
subCateQueue.push(msg);
}
if(catesQueue.length) {
c.send(catesQueue.shift());
} else if(subCateQueue.length) {
var list = subCateQueue.shift();
list.type = list.dir.indexOf('article') > -1 ? "article" : "imgs";
c.send(list);
} else {
console.log(msg.dir + ' done.');
}
} else {
console.log(msg);
}
});
}
}
} else if(cluster.isWorker) {
process.on('message', function(msg) {
var type = msg.type;
var url = msg.url;
var dir = msg.dir;
switch(type) {
case "list":
getList(url).then(function(data){
msg.subCatePages = data;
process.send(msg);
});
break;
case "article":
if(!fs.existsSync(msg.dir)) mkdirp.sync(msg.dir);
if(msg.subCatePages && msg.subCatePages.length) {
getSubCateList(msg).then(function(){
process.send("\n\n" + msg.dir + " OVER\n\n");
});
} else {
process.send("\n\n" + msg.dir + " OVER\n\n");
}
break;
case "imgs":
default:
process.send(msg);
}
});
}
}


// GET sub cate
function getList(url) {

return new Promise(function(resolve, reject){
process.send("Process: " + url);
request({
url: url,
timeout: 8E3
}, function(err, res, body) {
if(err || !body) {
resolve(); return
}
resolve(cheerio.load(body, {
normalizeWhitespace: false,
decodeEntities: false
}));
});
}).then(function($){
if(!$ || !$.html()) {
return [];
}
var num = +$(".num").eq(0).attr("href").split("_")[2].split(".")[0];
var ret = [];
while(num--) {
ret.push(url.replace(/_\d+/, function($0, $1) {
return $0 + (num == 0 ? "" : "_" + num);
}));
}
return ret;
});
}

// GET sub cate list
function getSubCateList(msg) {
return !msg.subCatePages.length ? Promise.resolve()
: new Promise(function(resolve, reject){
var url = msg.subCatePages.shift();
process.send("getSubCateList Process: " + url + ", type: " + msg.type);
request({
url: url,
timeout: 5E3
}, function(err, res, body) {
if(err || !body) {
resolve(); return
}
resolve(cheerio.load(body, {
normalizeWhitespace: false,
decodeEntities: false
}));
});
}).then(function($){
if(!$ || !$.html()) {
return getSubCateList(msg);
}
var details = [];
$("td a[href^='/article']").each(function(){
details.push(baseURL + $(this).attr("href"));
});
return getContent(details, msg).then(function(msg){
getSubCateList(msg);
});
}).catch(function(){
return getSubCateList(msg);
});
}

// GET content
function getContent(queue, msg) {
console.log("\n" + queue.length + "\n");
return !queue.length ? Promise.resolve(msg)
: new Promise(function(resolve, reject){
var url = queue.shift();
process.send("getContent Process: " + url + ", type: " + msg.type);
request({
url: url,
timeout: 5E3
}, function(err, res, body) {
if(err || !body) {
resolve(); return
}
resolve(cheerio.load(body, {
normalizeWhitespace: false,
decodeEntities: false
}));
});
}).then(function($){
if(!$ || !$.html()) {
return getContent(queue, msg);
}
if(msg.type == "article") {
var ctt = $("#MyContent").html();
var title = $(".title").text();
if(ctt) {
ctt = "<style>.body{-webkit-tap-highlight-color:transparent;font-size:16px;color:#2f2f2f;background:#fff;font-family:Georgia,serif;}.content{padding:20px 5%;max-width:700px;margin:0 auto;line-height:1.5}h2{line-height:50px;font-size:24px;}</style><div class='content'><h2>" + title + "</h2>" + ctt + "</div>"
}
var file = path.join(msg.dir, title.replace(/[\*\&\\\/\?\|\:\<\>\n\.\ "'\,\(\)]/gim, "").toString() + ".html");
console.log('File Path: ' + file);
fs.writeFileSync(file, ctt, 'utf8');
return getContent(queue, msg);
} else if(msg.type == "imgs") {
var pics = [];
var title = $(".title").text();
var dir = path.join(msg.dir, title.replace(/[\*\&\\\/\?\|\:\<\>\n\.\ "'\,\(\)]/gim, "").toString());
if(!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
$("#MyContent img").each(function(){
var src = $(this).attr("src");
if(src && (pics.indexOf(src) == -1)) {
var file = path.join(dir, src.slice(src.lastIndexOf("/") + 1));
console.log('File Path: ' + file);
request(url).pipe(fs.createWriteStream(file));
}
});
return getContent(queue, msg);
}
}).catch(function(){
return Promise.resolve(msg);
});
}

// function getImg(queue, dir){

// }

if(cluster.isMaster) {
// Get the main categories.
var categories = {};
var promise = new Promise(function(resolve, reject){
request(baseURL, function(err, res, body){
resolve(body);
});
}).then(function(data){
var $ = cheerio.load(data, {
normalizeWhitespace: false,
decodeEntities: false
});
var cates = {};
$("#menu_box ul").each(function(){
var cate;
var subCate = {};
var links = $(this).find("li a");
if(links.length) {
links.each(function(){
var text = $(this).text();
var href = $(this).attr('href');
if(href && href.indexOf('/') > -1) {
subCate[text] = baseURL + href;
} else {
cate = text;
}
});
cates[cate] = subCate;
}
});
// Enter spider
console.log("Start Spider Man");
run(cates);
});
} else {
run();
}

Nginx 开启本地代理

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net
本地目录结构:

1
2
3
4
5
6
7
8
├── nginx
│ ├── ca.crt
│ ├── ca.srl
│ ├── nginx.conf
│ ├── nginx.log
│ ├── server.crt
│ ├── server.csr
│ └── server.key

Nginx 配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
worker_processes auto;
pid nginx.pid;

events {
# 需要保留这一个段落,可以为空
}
http {
access_log nginx.log;
server {
listen 80;
listen 443 default ssl;
server_name barret.m.taobao.com;
ssl_certificate server.crt;
ssl_certificate_key server.key;
location / {
proxy_pass http://127.0.0.1:3333/;
}
}
}

package.json 的 script 增加:

1
2
3
"nginx_start": "sudo nginx -p ${PWD}/nginx -c ${PWD}/nginx/nginx.conf",
"nginx_stop": "sudo nginx -p ${PWD}/nginx -c ${PWD}/nginx/nginx.conf -s stop",
"nginx_reload": "sudo nginx -p ${PWD}/nginx -c ${PWD}/nginx/nginx.conf -s reload"

Attention:在项目下增加一个 nginx 目录。

证书生成

  1. 生成server.key

$ openssl genrsa -des3 -out server.key 2048

以上命令是基于des3算法生成的rsa私钥,在生成私钥时必须输入至少4位的密码。

  1. 生成无密码的server.key

$ openssl rsa -in server.key -out server.key

  1. 生成CA的crt

$ openssl req -new -x509 -key server.key -out ca.crt -days 3650

  1. 基于ca.crt生成csr

$ openssl req -new -key server.key -out server.csr

命令的执行过程中依次输入国家、省份、城市、公司、部门及邮箱等信息。

  1. 生成crt(已认证)

$ openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey server.key -CAcreateserial -out server.crt

Nginx使用url参数做反射代理

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
server {
server_name www.demo.com;
listen 80;

location / {
# 配置默认ip
set $default_ip 127.0.0.1;

# 配置默认port
set $default_port 8080;

# 如果url中包含ip=x
if ($request_uri ~* ip=(.+?)(&|$)) {
set $default_ip $1;
}

# 如果url中包含port=1
if ($request_uri ~* port=(\d+?)(&|$)) {
set $default_port $1;
}

# 配置代理参数
proxy_set_header Connection "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;

# 代理
proxy_pass http://$default_ip:$default_port;
}
}

使用方式:

1
2
3
4
5
6
7
8
9
10
11
// 使用默认值
www.demo.com

// 使用配置ip
www.demo.com/?ip=127.0.0.1

// 使用配置port
www.demo.com/?port=88

// IP+port
www.demo.com/?port=88&ip=127.0.0.01