tsorn
tsorn

Reputation: 3625

NodeJs are module loaded in order?

I use the module tough-cookie-filestore which saves cookies to a local file. When setting request to use this cookie jar, it requires that the file already exists on disk. As I use this cookie jar in multiple modules, I want to avoid a big block of code at the top of my modules which checks if the cookie file exists and if not creates it, and so I made a module initcookie.js that does this.

My question is, is this a safe and good way to do this? initcookie.init() makes sure that the file exists, but can I be sure that it is run before new FileCookieStore(config.cookiePath) is executed?

var initcookie = require('../initcookie.js').init()
var config = require('../config.js')
var FileCookieStore = require('tough-cookie-filestore')
var request = require('request')
var j = request.jar(new FileCookieStore(config.cookiePath))
request = request.defaults({ jar: j })

Where initcookie.js is:

var config = require('./config.js')
var fs = require('fs')

// Initialize cookie file which stores the login info
exports.init = function () {
  try {
    fs.openSync(config.cookiePath, 'r')
  } catch (e) {
    if (e.code === 'ENOENT') {
      // File not found, so make one
      fs.writeFileSync(config.cookiePath, '', { flags: 'wx' }, function (err) {
        if (err) { throw (err) }
      })
    } else {
      throw (e)
    }
  }
}

Upvotes: 0

Views: 673

Answers (1)

Isaac Madwed
Isaac Madwed

Reputation: 1006

This way will work, but isn't the best way to do this. fs.writeFileSync and fs.openSync will make sure that your code executes synchronously, but it would be better to use async so you aren't holding up the thread. You could write

var config = require('./config.js')
var fs = require('fs')

// Initialize cookie file which stores the login info
exports.init = function () {
  return new Promise(function (resolve, reject) {
    try {
      fs.openSync(config.cookiePath, 'r')
      resolve()
    } catch (e) {
      if (e.code === 'ENOENT') {
        // File not found, so make one
        fs.writeFile(config.cookiePath, '', { flags: 'wx' }, function (err) {
          if (err) { reject(err) }
          else { resolve() }
        })
      } else {
        reject(e)
      }
    }
  }
}

This way you can use Promises in your other files and be sure cookiePath is created without holding up the thread.

The only issue I could see you running into would be if async leads you to run this function a bunch of times before it completes and so create a race condition. To avoid that I would only call this function once at the beginning of the program and put everything else in the success function of that promise.

Upvotes: 1

Related Questions