1

I've created a helper app with Xcode. It's a command line app that keeps running using RunLoop (because it will do Bluetooth things in the background).

I want to spawn this app using node.js and read its output. I've sucessufully done this with other applications using the spawn method. However, with this MacOS app nothing is visible until the app finishes.

My node.js code:

const { spawn } = require('node:child_process')
const child = spawn(PROCESS)
child.stdout.on('data', data => {
  console.log(data.toString());
})

My Swift code (helper app):

import Foundation

var shouldKeepRunning = true

print("app started")

let controller = Controller()

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(10)) {
    shouldKeepRunning = false
}

while shouldKeepRunning == true && RunLoop.current.run(mode: RunLoop.Mode.default, before: Date.distantFuture) {

}

In node.js app started is only printed after 10 seconds, when the app finishes. When running the app using Terminal, I see app started immediately.

Does anyone know why this happens and how it can be solved?

Thanks!

Sam
  • 5,375
  • 2
  • 45
  • 54

1 Answers1

1

This question is actually the same: swift "print" doesn't appear in STDOut but 3rd party c library logs do when running in docker on ECS but instead of node.js Docker is not logging the output.

I fixed it by adding the following to the top of my code:

setbuf(stdout, nil)

This will make print() write to stdout directly without waiting for some buffer to be full first.

Sam
  • 5,375
  • 2
  • 45
  • 54