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
2

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.