Skip to content

Latest commit

 

History

History
104 lines (74 loc) · 3.2 KB

2016-12-07-nodejs.md

File metadata and controls

104 lines (74 loc) · 3.2 KB

nodejs 查漏

querystring.parse(str[, sep[, eq[, options]]])

> querystring.parse('a:1;b:2;c:3', ';', ':')
{ a: '1', b: '2', c: '3' }

console.dir(obj[, options])

timeout.unref()

const timer = setInterval(() => {
  doSth();
}, 1000 * 60 * 60);
timer.unref();

当代码中有一段定时任务被执行时,nodejs 进程会一直跑着,即使 event loop 中已经没有其他需要执行的任务了。如果你想要在 event loop 中没有需要执行的其他任务时,程序可以不被该段定时任务影响直接退出,你可以调用该定时器的 unref 方法。

net.isIP(input)

> require(`net`).isIP('zaraguo')
0
> require(`net`).isIP('1.1.1.1')
4
> require(`net`).isIP('2001:DB8:2de:0:0:0:0:e13')
6

os.EOL

一个指代不同操作系统下换行符的变量:

  • \n on POSIX
  • \r\n on Windows

http.STATUS_CODES

返回 HTTP 状态码 code 到各自简介的键值对 。

process.on('uncaughtException', console.error)

这真是相当粗鲁。

dns.lookup(hostname[, options], callback)

> require('dns').lookup('huaban.com', function () { console.log(arguments); })
> { '0': null, '1': '115.231.100.85', '2': 4 }

node 不会缓存 dns.lookup 的结果,你可以自己缓存起来。

fs 模块在不同操作系统下的问题

  • fs.stat(path, callback) 回调函数返回的 stats 对象的 mode 属性值在 Windows 和其他操作系统下可能不同。
  • fs.lchmod(path, mode, callback) 只在 macOS 下有用。
  • fs.symlink(target, path[, type], callback) 仅在 windows 下支持 type 参数。type 参数可以被设置为 'dir','file',或者 'junction' (默认为 'file')。
  • fs.watch(filename[, options][, listener]) 仅在 macOS 和 Windows 下支持 options 中的 recursive 设置。在 Linux 和 Windows 下其回调函数 有可能 会返回该文件名。WTF,也许你需要 chokidar
  • fs.open(path, flags[, mode], callback) 仅在 FreeBSD 和 Windows 下支持 flag 为 a+。
  • 在 Linux 下设置 fs.write(fd, buffer[, offset[, length[, position]]], callback) 的 position,并以追加模式打开,那么 position 参数将被忽略,继续以尾部追加方式写入。

repl 小技巧

  • .load someFile.js 将 someFile.js 中的内容逐行载入到 repl 中进行执行。

  • .editor 进入多行编辑状态,^D 结束,^C 退出。

  • .clear

    • 如果用 node 命令启动的 repl, 此时 .clear 相当于 .break。
    • 如果在用 repl.start() 启动的 repl 中,.clear 表示 .break,并且清空局部变量。
  • ~/.node_repl_history 中存放着你在 node repl 下执行的命令。设置 NODE_REPL_HISTORY="" 可以使得命令不被放入改历史文件中。

  • repl 启动时,已经将原生模块都载入了进来了。

  • _ 代表最近在 repl 中执行的返回值,但是如果 _ 被明确赋值了,这个功能就失效了。

> 2 ** 2
4
> _
4
> _ = 1
Expression assignment to _ now disabled.
1
> 2 ** 2
4
> _
1

参考

base on 19 things I learnt reading the NodeJS docs

1489 days left