0

Folks, given the following code... how would one re-use the returnResult and returnError functions? Is it possible to have their scope be global to all files that are required.

fs = require 'fs'

module.exports.syncJSON = (req, res)->
    returnResult = (data) ->
        res.send data

    returnError = (data) ->
        res.send data

    jsonFileContents = fs.readFileSync('sample.json', 'utf8')
    returnResult(jsonFileContents)

module.exports.asyncJSON = (req, res)->
    fs.readFile 'sample.json', (err, data) -> 
        if err
            returnError(err)
        else
            returnResult(data.toString())

    returnResult = (data) ->
        res.send data

    returnError = (data) ->
        res.send data
Cmag
  • 14,946
  • 25
  • 89
  • 140

1 Answers1

1

I think what you're asking about is how to use returnError and returnResult in both of the exports (.asyncJSON and .syncJSON). Globals are generally a bad idea. What if someone else overwrites your global? You'll have a weird and intermittent failure. If so, all you need to do is move them outside their current scope and pass in the response object:

s = require 'fs'

returnResult = (res, data)->
  res.send data
returnError = (res, err) -> 
  res.send err

module.exports.syncJSON = (req, res)->
  jsonFileContents = fs.readFileSync('sample.json', 'utf8')
  returnResult(res, jsonFileContents)

module.exports.asyncJSON = (req, res)->
  fs.readFile 'sample.json', (err, data) -> 
    if err
      returnError(res, err)
    else
      returnResult(res, data.toString())
jcollum
  • 43,623
  • 55
  • 191
  • 321