Created
December 8, 2012 17:31
-
-
Save mainiak/4241112 to your computer and use it in GitHub Desktop.
file seeking in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env coffee | |
### | |
in native fs, | |
we could set position from where to read, | |
but we have to track it manually | |
if run many times with position null, | |
and once with position=0, it doesn't reset to 0 | |
as expected, but it remains same ... -_- sigh | |
for second mode testing run: npm install fs-ext | |
and set SECOND_MODE to true | |
### | |
FS = require 'fs-ext' # includes nodejs core fs module | |
UTIL = require 'util' | |
FILE = 'dummy.txt' | |
BUFF_SIZE = 6 | |
CYCLES = 20 | |
LOOP = true | |
SEEK_SET = 0 | |
SECOND_MODE = false | |
fd = FS.openSync FILE, 'r' | |
buff = new Buffer BUFF_SIZE | |
position = 0 | |
readNative = -> | |
#console.log UTIL.inspect fstat FS.fstatSync fd # doesn't give current position | |
#UTIL.debug 'position: ' + position # XXX | |
bytesRead = FS.readSync fd, buff, 0, buff.length, position | |
# read from start | |
if LOOP and bytesRead is 0 | |
position = 0 | |
return readNative() | |
position += bytesRead | |
#UTIL.debug "bytesRead: #{bytesRead}, position: #{position}" # XXX | |
return bytesRead | |
# https://github.com/baudehlo/node-fs-ext | |
readFsExt = -> | |
bytesRead = FS.readSync fd, buff, 0, buff.length, null | |
# read from start | |
if LOOP and bytesRead is 0 | |
FS.seekSync fd, 0, SEEK_SET | |
return readFsExt() | |
return bytesRead | |
read = -> | |
if SECOND_MODE | |
bytesRead = readFsExt() | |
else | |
bytesRead = readNative() | |
if bytesRead is 0 | |
console.log 'Reading is over!' | |
return | |
stuff = '' | |
stuff += ' ' for [0..(BUFF_SIZE-bytesRead)] if bytesRead < BUFF_SIZE | |
console.log "|#{buff.toString('utf8', 0, bytesRead).replace(/\n/, '') + stuff}|" | |
read() for [0..CYCLES] # ruby: CYCLES.times read() | |
FS.closeSync fd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment