# How to use NonBlockingFileIO for repeated writes

**URL:** <https://forums.swift.org/t/how-to-use-nonblockingfileio-for-repeated-writes/36206>\
**Category:** SwiftNIO\
**Created:** [May 6, 2020, 9:37am UTC](https://forums.swift.org/t/how-to-use-nonblockingfileio-for-repeated-writes/36206 "2020-05-06T09:37:47Z")\
**Posts on this page:** 1\
**Showing post:** 24

<div class="post-metadata">

**Author:** ![tanner0101](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tanner0101/32/675_2.png) [@tanner0101](https://forums.swift.org/u/tanner0101)\
**Post date:** [May 27, 2020, 7:45pm UTC](https://forums.swift.org/t/how-to-use-nonblockingfileio-for-repeated-writes/36206/24 "2020-05-27T19:45:00Z")

</div>

I've just released [Release Refactor request body streaming state handling · vapor/vapor · GitHub](https://github.com/vapor/vapor/releases/tag/4.7.0) which addresses the `Precondition failed: blacklisted errno 9 Bad file descriptor` error. Request's `body.drain` method will now wait until the previously returned future has completed before calling the handler again. This means that simply returning the file io write future in the drain handler will now result in correct behavior.

I've also included a streaming file upload example in the `Development` module: [vapor/routes.swift at main · vapor/vapor · GitHub](https://github.com/vapor/vapor/blob/master/Sources/Development/routes.swift#L180-L209)

Copying it here for posterity:

```swift
app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in
    return req.application.fileio.openFile(
        path: "/Users/tanner/Desktop/foo.txt",
        mode: .write,
        flags: .allowFileCreation(),
        eventLoop: req.eventLoop
    ).flatMap { fileHandle in
        let promise = req.eventLoop.makePromise(of: HTTPStatus.self)
        req.body.drain { part in
            switch part {
            case .buffer(let buffer):
                return req.application.fileio.write(
                    fileHandle: fileHandle,
                    buffer: buffer,
                    eventLoop: req.eventLoop
                )
            case .error(let error):
                promise.fail(error)
                try! fileHandle.close()
                return req.eventLoop.makeSucceededFuture(())
            case .end:
                promise.succeed(.ok)
                try! fileHandle.close()
                return req.eventLoop.makeSucceededFuture(())
            }
        }
        return promise.futureResult
    }
}

```

Thanks to @johannesweiss for sharing [swift-nio-examples/backpressure-file-io-channel at main · apple/swift-nio-examples · GitHub](https://github.com/apple/swift-nio-examples/tree/master/backpressure-file-io-channel) which I referenced heavily for Vapor's updated body stream state machine.

---

_[View the full topic](https://forums.swift.org/t/how-to-use-nonblockingfileio-for-repeated-writes/36206)._
