Skip to content

Commit

Permalink
Add FileIO.write
Browse files Browse the repository at this point in the history
  • Loading branch information
t-ae committed Jun 30, 2020
1 parent dc2aa1e commit 953d5e0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Sources/Vapor/Utilities/FileIO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,23 @@ public struct FileIO {
return self.request.eventLoop.makeFailedFuture(error)
}
}

/// Write the contents of buffer to a file at the supplied path.
///
/// - parameters:
/// - path: Path to file on the disk.
/// - buffer: The `ByteBuffer` to write.
/// - returns: `Future` that will complete when the file write is finished.
public func write(to path: String, buffer: ByteBuffer) -> EventLoopFuture<Void> {
do {
let fd = try NIOFileHandle.init(path: path, mode: .write, flags: .allowFileCreation())
let done = io.write(fileHandle: fd, buffer: buffer, eventLoop: self.request.eventLoop)
done.whenComplete { _ in
try? fd.close()
}
return done
} catch {
return self.request.eventLoop.makeFailedFuture(error)
}
}
}
19 changes: 19 additions & 0 deletions Tests/VaporTests/FileTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ final class FileTests: XCTestCase {
XCTAssertContains(res.body.string, test)
}
}

func testFileWrite() throws {
let app = Application(.testing)
defer { app.shutdown() }

let request = Request(application: app, on: app.eventLoopGroup.next())

let data = "Hello".data(using: .utf8)!
let path = "/tmp/fileio_write.txt"

try request.fileio.write(to: path, buffer: ByteBuffer(data: data)).wait()
defer { try? FileManager.default.removeItem(atPath: path) }

let content = try request.fileio.collectFile(at: path).wait()

let result = Data(content.readableBytesView)

XCTAssertEqual(result, data)
}

func testPercentDecodedFilePath() throws {
let app = Application(.testing)
Expand Down

0 comments on commit 953d5e0

Please sign in to comment.