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

Local files support #10

Open
mitar opened this issue Sep 19, 2014 · 1 comment
Open

Local files support #10

mitar opened this issue Sep 19, 2014 · 1 comment

Comments

@mitar
Copy link

mitar commented Sep 19, 2014

Just to document here for others. I am using the following code for local files. It works "good enough", but probably one could do smarter things with settings _require and _response to some random values, just to be sure.

fs = require 'fs'

URL_BASE = '/srv/files/'

class LocalFilesXMLHttpRequest extends XMLHttpRequest
  _sendRelative: (data) ->
    fullUrl = url.resolve URL_BASE, @_url.href
    @_url = @_parseUrl fullUrl

    @_sendFile data

  _sendFile: (data) ->
    unless @_method is 'GET'
      throw new NetworkError "The file protocol only supports GET"

    if data? and (@_method is 'GET' or @_method is 'HEAD')
      console.warn "Discarding entity body for #{ @_method } requests"
      data = null
    else
      # Send Content-Length: 0
      data or= ''

    @upload._setData data
    @_finalizeHeaders()

    @_request = null
    @_dispatchProgress 'loadstart'

    if @_sync
      defer = (f) ->
        f()
    else
      defer = process.nextTick

    defer =>
      try
        data = fs.readFileSync @_url.pathname
      catch error
        # TODO: Should set status based on the error
        data = new Buffer "#{ error }"
        status = 404

      @_response = null
      @status = status
      @statusText = http.STATUS_CODES[@status]
      @_totalBytes = data.length
      @_lengthComputable = true

      @_setReadyState XMLHttpRequest.HEADERS_RECEIVED

      @_onHttpResponseData null, data
      @_onHttpResponseEnd null
@letmaik
Copy link

letmaik commented Aug 25, 2015

Desperately waiting for built-in file:// support as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants