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" )
}
} ;