ntp time sync
0.4.1
Node.JS 模块从 NTP 服务器获取当前时间并返回偏移信息。
NTP 需要 UDP,这在浏览器上下文中不可用!
# using Yarn
$ yarn add ntp-time-sync
# using NPM
$ npm install ntp-time-sync
考虑使用该库作为单例,这样就不会每次调用getTime
都会触发新的 NTP 包。库本身将管理最小/最大轮询时间。
向多个 NTP 时间服务器发出多个请求,并且响应将被聚合。
// ES6:
import { NtpTimeSync } from "ntp-time-sync" ;
// pre-ES6:
// const NtpTimeSync = require("ntp-time-sync").NtpTimeSync;
const timeSync = NtpTimeSync . getInstance ( ) ;
// request 1
timeSync . getTime ( ) . then ( function ( result ) {
console . log ( "current system time" , new Date ( ) ) ;
console . log ( "real time" , result . now ) ;
console . log ( "offset in milliseconds" , result . offset ) ;
} )
// request 2, will use cached offset from previous request
timeSync . getTime ( ) . then ( function ( result ) {
console . log ( "current system time" , new Date ( ) ) ;
console . log ( "real time" , result . now ) ;
console . log ( "offset in milliseconds" , result . offset ) ;
} )
// ES2017 style
const result = await timeSync . getTime ( ) ;
console . log ( "real time" , result . now ) ;
<ntpTimeSyncInstance>.getTime()
返回一个Promise
对象,该对象最终将使用包含以下信息的对象进行解析:
财产 | 描述 |
---|---|
now | 当前 NTP 时间(“实时”) |
offset | 计算本地系统时间和 NTP 时间之间的偏移量 |
<ntpTimeSyncInstance>.now()
返回一个Date
对象,其中包含调用该函数时的正确时间。与getTime()
相反,它将返回 Promise 得到解决时的正确时间。
您可以将自定义选项传递给NtpTimeSync
或NtpTimeSync.getInstance(options)
的构造函数。这些将与以下默认值合并:
const defaultOptions = {
// list of NTP time servers, optionally including a port (defaults to 123)
servers : [
"0.pool.ntp.org" ,
"1.pool.ntp.org" ,
"2.pool.ntp.org" ,
"3.pool.ntp.org"
] ,
// required amount of valid samples in order to calculate the time
sampleCount : 8 ,
// amount of time in milliseconds to wait for a single NTP response
replyTimeout : 3000 ,
// defaults as of RFC5905
ntpDefaults : {
port : 123 ,
version : 4 ,
tolerance : 15e-6 ,
minPoll : 4 ,
maxPoll : 17 ,
maxDispersion : 16 ,
minDispersion : 0.005 ,
maxDistance : 1 ,
maxStratum : 16 ,
precision : - 18 ,
referenceDate : new Date ( "Jan 01 1900 GMT" )
}
} ;