Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,13 @@ export class ViteNodeRunner {

try {
const fn = vm.runInThisContext(code, options)
await fn(...Object.values(context))
// Execute the module body on a macrotask instead of synchronously inside
// V8's microtask checkpoint. This preserves Node.js's event loop contract
// that `process.nextTick` callbacks run before Promise/queueMicrotask
// callbacks, matching how native CommonJS entry modules are executed.
await new Promise<void>((resolve) => {
setImmediate(() => resolve(fn(...Object.values(context))))
})
}
finally {
this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo())
Expand Down
13 changes: 13 additions & 0 deletions test/src/event-loop-order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const order: string[] = []

Promise.resolve().then(() => order.push('P'))
queueMicrotask(() => order.push('Q'))
process.nextTick(() => order.push('N'))
setImmediate(() => order.push('I'))
setTimeout(() => order.push('T'), 0)
order.push('S')

setTimeout(() => {
// eslint-disable-next-line no-console
console.log(order.join(''))
}, 100)
25 changes: 25 additions & 0 deletions test/test/event-loop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { resolve } from 'pathe'
import { describe, expect, it } from 'vitest'
import { runViteNodeCli } from '../test-utils'

const entryPath = resolve(import.meta.dirname, '../src/event-loop-order.ts')

describe('event loop ordering', () => {
// The module in `src/event-loop-order.ts` schedules:
// Synchronous code (S), process.nextTick (N), Promise (P),
// queueMicrotask (Q), setImmediate (I), setTimeout (T).
//
// Node.js guarantees that `process.nextTick` callbacks run before the
// microtask queue (Promises / queueMicrotask). The deterministic part of
// that contract is confirmed here: "N" must appear before both "P" and "Q".
// The tail ordering of the timer phase ("T") vs the check phase ("I") is not
// guaranteed by the event loop and is flaky under load, so it is not asserted.
it('runs process.nextTick before microtasks', async () => {
const cli = await runViteNodeCli(entryPath)
const out = cli.stdout.trim()

expect(out.startsWith('SNPQ')).toBe(true)
expect(out.indexOf('N')).toBeLessThan(out.indexOf('P'))
expect(out.indexOf('N')).toBeLessThan(out.indexOf('Q'))
})
})