• npm从git地址安装
    npm install –save git+ssh:// 项目中模块依赖的地址也会被改成git地址

  • 怎样停止监听端口

    1
    2
    3
    var server = http.createServer();
    server.listen(...);
    server.stop(); // 停止监听

website

product

  • koa2-remote
  • md-hexo
    • 为markdown文件增加title和tags,date标签
    • 默认忽略node_modules目录

filename: 当前文件路径
module.filename 等同于
filename
__dirname: 当前文件所在文件夹
process.cwd() 执行当前命令所在的目录
require.main.filename 用node启动的module的filename,如 node xxx,这里的filename就是这个xxx。
require()方法的坐标路径是:module.filename;fs.readFile()的坐标路径是:process.cwd()。

背景

在一个electron项目中,需要引入一些模板文件,之前处理一直是require引入后使用webpack进行打包.. 但是既然是electron环境,支持node,为什么就不能让node的require直接引入模板文件呢?实际上就是不想打包, 不想在支持node的环境中使用webpack.. so,开始折腾

相关资料

Almost any Node.js developer can tell you what the require() function does, but how many of us actually know how it works?
We use it every day to load libraries and modules, but its behavior otherwise is a mystery.
几乎所有的nodejs开发者都知道require()是做什么的,但是有多少知道它是如何共走的呢?
我们每天使用它加载库和模块,但是他的工作原理依然很神秘.

Curious, I dug into Node core to find out what was happening under the hood.
But instead of finding a single function, I ended up at the heart of Node’s module system: module.js.
The file contains a surprisingly powerful yet relatively unknown core module that controls the loading, compiling, and caching of every file used.
require(), it turned out, was just the tip of the iceberg.
因为好奇, 我深入node的核心来查找require后到底发生了什么.
本来以为会发现一个单独的函数处理,结果确是node的模块系统: module.js.
这个文件是一个非常强大的核心模块, 它控制着我们所有文件的加载、编译、缓存.
原来, require只是其中的冰山一角.

module.js
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
// …
The Module type found in module.js has two main roles inside of Node.js.
First, it provides a foundation for all Node.js modules to build off of.
Each file is given a new instance of this base module on load, which persists even after the file has run.
This is why we are able attach properties to module.exports and return them later as needed.
module.js的Module在node.js中有两个重要作用.
第一, 它提供了一个模块编译的基础.
每一个文件加载时都将是一个新的module实例, 并且在文件执行完只有仍然存在.
这就是为什么我们能够把属性添加到module.exports并且按需要返回它们.

The module’s second big job is to handle Node’s module loading mechanism.
The stand-alone require function that we use is actually an abstraction over module.require, which is itself just a simple wrapper around Module._load.
This load method handles the actual loading of each file, and is where we’ll begin our journey.
Module的第二个作用是处理node的模块加载机制.
我们使用的require函数实际上是module.require的一个抽象, 是对Module._load的一个简单包装.
load方法处理每个文件如何加载,这就是我们开始旅程的地方.

Module._load
Module._load = function(request, parent, isMain) {
// 1. Check Module._cache for the cached module.
// 2. Create a new Module instance if cache is empty.
// 3. Save it to the cache.
// 4. Call module.load() with your the given filename.
// This will call module.compile() after reading the file contents.
// 5. If there was an error loading/parsing the file,
// delete the bad module from the cache
// 6. return module.exports
};
Module._load is responsible for loading new modules and managing the module cache.
Caching each module on load reduces the number of redundant file reads and can speed up your application significantly.
In addition, sharing module instances allows for singleton-like modules that can keep state across a project.
Module._load负责加载新模块和管理模块缓存.
缓存模块可以减少文件读取并且提高程序的执行速度.
此外, 单独模块的共享实例能够在整个项目中缓存状态.

If a module doesn’t exist in the cache, Module._load will create a new base module for that file.
It will then tell the module to read in the new file’s contents before sending them to module._compile.[1]
如何一个模块在缓存中不存在, Module._laod将为这个文件新建一个基础模块.
读取文件的内容之后才会执行module._compile进行编译.

If you notice step #6 above, you’ll see that module.exports is returned to the user.
This is why you use exports and module.exports when defining your public interface, since that’s exactly what Module._load and then require will return.
I was surprised that there wasn’t more magic going on here, but if anything that’s for the better.
如果你注意到了上面的第#6步, 你将会发现module.exports被返回给用户.
这就是为什么使用exports和module.exports来定义公共接口,因为这就是Module._load加载后将返回他们.
我很惊讶, 这里没有更多魔术般的处理, 但是有什么更好的呢.

module._compile
Module.prototype._compile = function(content, filename) {
// 1. Create the standalone require function that calls module.require.
// 2. Attach other helper methods to require.
// 3. Wraps the JS code in a function that provides our require,
// module, etc. variables locally to the module scope.
// 4. Run that function
};
This is where the real magic happens. First, a special standalone require function is created for that module.
THIS is the require function that we are all familiar with.
While the function itself is just a wrapper around Module.require, it also contains some lesser-known helper properties and methods for us to use:

require(): Loads an external module
require.resolve(): Resolves a module name to its absolute path
require.main: The main module
require.cache: All cached modules
require.extensions: Available compilation methods for each valid file type, based on its extension
Once require is ready, the entire loaded source code is wrapped in a new function, which takes in require, module, exports, and all other exposed variables as arguments. This creates a new functional scope just for that module so that there is no pollution of the rest of the Node.js environment.

(function (exports, require, module, filename, dirname) {
// YOUR CODE INJECTED HERE!
});
Finally, the function wrapping the module is run.
The entire Module._compile method is executed synchronously, so the original call to Module._load just waits for this code to run before finishing up and returning module.exports back to the user.

Conclusion
And so we’ve reached the end of the require code path, and in doing so have come full circle by creating the very require function that we had begun investigating in the first place.

If you’ve made it all this way, then you’re ready for the final secret: require(‘module’).
That’s right, the module system itself can be loaded VIA the module system. INCEPTION. This may sound strange, but it lets userland modules interact with the loading system without digging into Node.js core. Popular modules like mockery and rewire are built off of this.[2]

If you want to learn more, check out the module.js source code for yourself.
There is plenty more there to keep you busy and blow your mind.
Bonus points for the first person who can tell me what ‘NODE_MODULE_CONTEXTS’ is and why it was added.

[1] The module._compile method is only used for running JavaScript files. JSON files are simply parsed and returned via JSON.parse()

[2] However, both of these modules are built on private Module methods, like Module._resolveLookupPaths and Module._findPath. You could argue that this isn’t much better…

相对于父元素宽度的:
[max/min-]width、left、right、padding、margin 等;

相对于父元素高度的:
[max/min-]height、top、bottom 等;

相对于继承字号的:
font-size 等;

相对于自身字号的:
line-height 等;

相对于自身宽高的:
border-radius、background-size、transform: translate()、transform-origin、zoom、clip-path 等;

特殊算法的:
background-position(方向长度 / 该方向除背景图之外部分总长度 * 100)、
filter 系列函数等;

如果自身设置 position: absolute,“父元素”指:破坏文档流的div高度设为百分比是相对谁而言的? - Boringer 的回答
如果 position: fixed,“父元素”指视口。

作者:Boringer
链接:https://www.zhihu.com/question/36079531/answer/65809167
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

css3

position: sticky;
position: -webkit-sticky;

滚动定位: 当页面元素滚动到视觉范围之外时,元素改为fixed定位

ios滚动时事件处理

ios滚动时无触发scroll事件:可以修改为绑定touchmove事件,但是滑动后惯性滚动时还是不会触发事件
ios滚动时position从fixed切换为relative会有问题, 可以使用css3

mac同一程序不同窗口切换快捷键

commond + ~

webstrom format不工作

原因: 插件失效

shell

  • 获取日期时间 d=date '+%Y-%m-%d %H:%M:%S'
  • 使用expect实现自动交互功能
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    # expect 示例1
    #! /usr/bin/expect
    expect << EOF
    spawn python upload.py -y
    expect "username:"
    send "myusename\r"
    expect "password:"
    send "mypassword\r"
    expect "New issue subject:"
    send "issuename\r"
    expect eof
    exit
1
2
3
4
5
6
7
8
9
# expect 示例2
spawn python upload.py -y
expect {
"username:" { send "myusename\r"; exp_continue}
"password:" { send "mypassword\r"; exp_continue }
"New issue subject:" {send "issuename\n"; exp_continue}
"please visit" {exit}
}

TCL (工具命令语言(Tool Command Language))

node错误处理

shell脚本 条件判断错误

[shell脚本报错:”[: =: unary operator expected”](http://blog.csdn.net/goodlixueyong/article/details/6564591)
在匹配字符串相等时,我用了类似这样的语句:

1
2
3
if [ $STATUS == "OK" ]; then
echo "OK"
fi

在运行时出现了 [: =: unary operator expected 的错误,就一直找不到原因,尝试了删除等号两侧的空格和括号里的空格都不管用,最后baidu了一下,才找到原因。把语句改成这样就不会出错了.

1
2
3
if [[ $STATUS = "OK" ]]; then
echo "OK"
fi

究其原因,是因为如果变量STATUS值为空,那么就成了 [ = “OK”] ,显然 [ 和 “OK” 不相等并且缺少了 [ 符号,所以报了这样的错误。当然不总是出错,如果变量STATUS值不为空,程序就正常了,所以这样的错误还是很隐蔽的。

或者用下面的方法也能避免这种错误:

1
2
3
if [ "$STATUS"x == "OK"x ]; then
echo "OK"
fi

当然,x也可以是其他字符。顺便提一点,shell中有没有双引号在很多情况下是一致的。

node同一个端口支持http和https(只能作为服务器,不能作为代理)

摘自:http://www.cnblogs.com/dojo-lzz/p/5479870.html
众所周知node是一个高性能的web服务器,使用它可以很简单的创建一个http或https的服务器。
比如一个很简单的http服务器:

1
2
3
4
5
6
7
8
9
var http = require('http');
var https = require('https');
var httpPort = 3345;
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hello world!');
}).listen(httpPort);

https服务器需要生成证书,详情请看这篇文章:HTTPS 的原理和 NodeJS 的实现。这里我们直接看最终成果,附件证书。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var https = require('https');
var fs = require('fs');
var httpsPort = 3346;
var options = {
key: fs.readFileSync('./cakey.pem'),
cert: fs.readFileSync('./cacert.pem')
};
var sserver = https.createServer(options, function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('secured hello world');
}).listen(httpsPort);

从上文我们可以看出,node生成的每个服务器必须分配一个端口。那么如果我们在工作中遇到一个需求:让同一个端口或地址既支持http协议又支持https协议,这时候我们该怎么办,有的同学很可能想到用nginx做反向代理,这不失为一个解决方案,但这也同样意味着增加了产品的复杂度,用户并不想去折腾ngnix。
办法是有的,原理就要搬出OSI的七层模型:
a8ec8a13632762d04284e772a1ec08fa503dc641
HTTP与HTTPS都属于应用层协议,所以只要我们在底层协议中进行反向代理,就可以解决这个问题! 刚好node可以让我们很方便的创建一个tcp服务器!

所以我们的核心代码如下:

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
var net = require('net');
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpPort = 3345;
var httpsPort = 3346;
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hello world!');
}).listen(httpPort);
var options = {
key: fs.readFileSync('./cakey.pem'),
cert: fs.readFileSync('./cacert.pem')
};
var sserver = https.createServer(options, function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('secured hello world');
}).listen(httpsPort);
net.createServer(function(socket){
socket.once('data', function(buf){
console.log(buf[0]);
// https数据流的第一位是十六进制“16”,转换成十进制就是22
var address = buf[0] === 22 ? httpsPort : httpPort;
//创建一个指向https或http服务器的链接
var proxy = net.createConnection(address, function() {
proxy.write(buf);
//反向代理的过程,tcp接受的数据交给代理链接,代理链接服务器端返回数据交由socket返回给客户端
socket.pipe(proxy).pipe(socket);
});
proxy.on('error', function(err) {
console.log(err);
});
});
socket.on('error', function(err) {
console.log(err);
});
}).listen(3344);

fis3打包单文件vue

nodejs异步改造为同步模块fibers

nodejs输出单行日志

1
2
3
4
5
6
7
8
9
10
11
12
// 使用前最好判断一下这三个函数是否存在
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(msg);
console.log(msg) == > process.stdout.write(msg + '\n')
// 输出区域的宽度和高度
process.stdout.on('resize', () => {
console.log('screen size has changed!');
console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});