Skip to content

Commit

Permalink
Add FileIO.writeFile (#2418)
Browse files Browse the repository at this point in the history
* Add FileIO.write

* Refactor

* Change signature

* Refine test

* Add code example

Co-authored-by: Tanner <tannernelson@gmail.com>
  • Loading branch information
t-ae and tanner0101 committed Jul 17, 2020
1 parent 98babd7 commit 562aca7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Sources/Vapor/Utilities/FileIO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,26 @@ public struct FileIO {
return self.request.eventLoop.makeFailedFuture(error)
}
}

/// Write the contents of buffer to a file at the supplied path.
///
/// let data = ByteBuffer(string: "ByteBuffer")
/// try req.fileio.writeFile(data, at: "/path/to/file.txt").wait()
///
/// - 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 writeFile(_ buffer: ByteBuffer, at path: String) -> EventLoopFuture<Void> {
do {
let fd = try NIOFileHandle(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)
}
}
}
16 changes: 16 additions & 0 deletions Tests/VaporTests/FileTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ 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"
let path = "/tmp/fileio_write.txt"

try request.fileio.writeFile(ByteBuffer(string: data), at: path).wait()
defer { try? FileManager.default.removeItem(atPath: path) }

let result = try String(contentsOfFile: path)
XCTAssertEqual(result, data)
}

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

0 comments on commit 562aca7

Please sign in to comment.