Skip to content

Commit

Permalink
Merge pull request #598 from luvit/fixes/add_writefilesync
Browse files Browse the repository at this point in the history
feat(fs): add writefilesync
  • Loading branch information
rphillips committed Jan 30, 2015
2 parents 5481f32 + 5d7c786 commit 200bcf4
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
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)

0 comments on commit 200bcf4

Please sign in to comment.