Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(fs): add writefilesync #598

Merged
merged 1 commit into from Jan 30, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 32 additions & 1 deletion app/modules/fs.lua
Expand Up @@ -412,7 +412,8 @@ function fs.WriteStream:open(callback)
if err then
self:destroy()
self:emit('error', err)
if callback then return callback(err) end
if callback then callback(err) end
return
end
self.fd = fd
self:emit('open', fd)
Expand Down Expand Up @@ -441,3 +442,33 @@ function fs.WriteStream:destroy()
self.fd = nil
end
end

fs.WriteStreamSync = fs.WriteStream:extend()
function fs.WriteStreamSync:initialize(path, options)
fs.WriteStream.initialize(self, path, options)
end
function fs.WriteStreamSync:open(callback)
local err
if self.fd then self:destroy() end
self.fd, err = fs.openSync(self.path, "a")
if err then
self:destroy()
self:emit('error', err)
if callback then callback(err) end
return
end
self:emit('open', self.fd)
if callback then callback() end
end
function fs.WriteStreamSync:_write(data, encoding, callback)
if not self.fd then
return self:once('open', bind(self._write, self, data, encoding, callback))
end
local written, err = fs.writeSync(self.fd, data, -1)
if err then
self:destroy()
return callback(err)
end
self.bytesWritten = self.bytesWritten + written
callback()
end
15 changes: 15 additions & 0 deletions tests/test-fs.lua
Expand Up @@ -208,4 +208,19 @@ require('tap')(function (test)
end))()
end)

test("writestream sync", function()
local stream, filename, writeStr, data

writeStr = "hello world"
filename = "testfile.txt"
fs.unlinkSync(filename)

stream = fs.WriteStreamSync:new("testfile.txt")
stream:write(writeStr)
stream:destroy()

data = fs.readFileSync(filename)
fs.unlinkSync(filename)
assert(data:find(writeStr) > -1)
end)
end)