Process.hrtime cannot be access inside js file

Hi

Within a javascript k6 project, the following line fails

const now = process.hrtime.bigint();

Error:
ReferenceError: process is not defined\n\tat file:///tmp/socket-test.js:63:19(93)\n\tat github.com/loadimpact/k6/js/common.Bind.func1 (native)\n\tat _default (file:///tmp/socket-test.js:42:33(50))\n" executor=ramping-vus scenario=default source=stacktrace

What’s the recommended way of accessing nanosecond time via k6 if not via process?

Hi there, welcome to the forum :slight_smile:

process is a Node.js module, and as k6 scripts do not run on Node.js, it is not supported.

The best you can do with the built-in JS modules is millisecond precision with e.g. Date.now().

As k6 is built with Go, which uses nanosecond precision, it should be fairly trivial to expose this via the new xk6 extension system. See this tutorial for a quick introduction.

Here’s a PoC:

// nstime.go
package nstime

import (
	"time"

	"github.com/loadimpact/k6/js/modules"
)

func init() {
	modules.Register("k6/x/nstime", new(NSTime))
}

type NSTime struct{}

func (n *NSTime) Now() int64 {
	return time.Now().UnixNano()
}
// script.js
import time from 'k6/x/nstime';

export default function () {
  console.log(time.now());
}

Running xk6 run script.js outputs:

INFO[0000] 1607445968992330500                           source=console

HTH,

Ivan

Thanks for respoonse, I’ll give this a go(pun intended)!

1 Like