Skip to content

Instantly share code, notes, and snippets.

@mainiak
Created December 8, 2012 17:31
Show Gist options
  • Save mainiak/4241112 to your computer and use it in GitHub Desktop.
Save mainiak/4241112 to your computer and use it in GitHub Desktop.
file seeking in nodejs
#!/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