Node.js 8.5
虽说前一阵子Node.js在国内技术圈掀起了不小的波澜,但最近 Node.js 发布了8.5版本,在这个版本里,Node 添加了3个激动人心的新特性。相信唱衰Node.js的看客们又要思量一下了。
支持 ES Module
此次版本迭代中,Node.js终于支持了开发者呼声最高的 ES 模块提案。这意味着,你可以直接使用import
关键字引入需要的模块。 Node 8.5 可以运行如下代码:
1
2
|
`
import
fs
from
'fs'
`
|
使用es模块,你需要注意,引入文件的扩展名应为 mjs
,同时使用 --experimental-modules
标识。
在 Node.js 中使用 ES 模块的限制:
import()
, V8引擎将在下一版本支持,import.meta
, V8引擎暂不支持,- 不支持
require('./foo.mjs')
参考文章:https://github.com/nodejs/node/pull/14369/files
性能监控
在 Node.js 8.5 版本中,新加入性能监控API 。
在 Node.js 8.5 中,可以调用 mark()
和 measure()
API,监控 Node.js 事件执行时间。
在 Node.js 8.5 中,你可以这样使用:
1
2
3
4
5
6
7
8
9
|
const
{
performance
}
=
require
(
'perf_hooks'
)
performance
.
mark
(
'A'
)
setTimeout
(
(
)
=
>
{
performance
.
mark
(
'B'
)
performance
.
measure
(
'A to B'
,
'A'
,
'B'
)
const
entry
=
performance
.
getEntriesByName
(
'A to B'
,
'measure'
)
console
.
log
(
entry
.
duration
)
}
,
10000
)
|
官方文档:https://nodejs.org/api/perf_hooks.html
参考文章:https://github.com/nodejs/node/pull/14680/files
fs
模块添加文件复制功能
Node.js 8.5 推出了更高级的文件系统,在这个版本你可以直接通过 fs
模块复制某个文件的代码:
1
2
3
4
5
6
7
8
9
10
|
const
fs
=
require
(
'fs'
)
fs
.
copyFile
(
'source.txt'
,
'destination.txt'
,
(
err
)
=
>
{
if
(
err
)
{
// handle error properly, not just console.log
return
console
.
error
(
err
)
}
console
.
log
(
'source.txt was copied to destination.txt'
)
}
)
|
参考文章:https://github.com/nodejs/node/pull/15034/files
通过这些新特性,Node开发者或许又要迎来第二春。