0

I got this code:

var log = (function () {
 'use strict';
 var fs = require('fs'), baseName='', path = require('path');
 fs.readFile('./config.json', {encoding : 'utf-8'}, function (err, data) {
            if (!err) {
                var parsedConfig = JSON.parse(data);
                logPath = parsedConfig.logFile;
                baseName = path.basename(logPath, '.log');
                if (logPath.length==0 )
                    logPath = './alteredFile.log';
            } else {
                throw err;
            }
        });
}());

var module;
module.exports = log;

I'm trying to set variable baseName but out side of fs.readFile callback it's not set and still empty! how can Iresolve this?

Super Hornet
  • 2,839
  • 5
  • 27
  • 55
  • 1
    Also note that IIFEs [aren't typically necessary with Node.js' module scope](http://stackoverflow.com/questions/21531329/are-node-js-modules-need-to-be-wrapped-inside-the-module-pattern) – Jonathan Lonowski Nov 06 '14 at 19:20

1 Answers1

1

baseName along with fs, and path would only be available within the scope of log function. If you want it available outside the scope of log (which includes fs.readFile) you must declare it within the broader scope that contains log (global scope if log itself is in global scope).

Mike Brant
  • 70,514
  • 10
  • 99
  • 103