Beispiel #1
0
  hasCached: function(category, hash, filename, cb) {
    var filePath = this.getCachedFilePath(category, hash, filename);

    fs.exists(filePath, function(exists) {
      return cb(exists, exists ? filePath : null);
    });
  },
 res.on('row', function(row) {
   var thisrow = row
   var filename = row['tumblrName']+"_"+row['post']+"_"+row['imageFilename']
   //util.debug("filename:"+filename)
   fs.exists(filename,function(exists){
     util.debug(filename+" exists:"+exists)
     if (exists===false) {
       // util.debug(filename+" exists")
       that.mariaClient.query('UPDATE Posts SET deleted=true WHERE imageURL="'
                             +thisrow['imageURL']
                             +'" AND tumblrName="'
                             +thisrow['tumblrName']
                             +'" AND post = "'+thisrow['post']+'"')
       .on('result',function(res) {
         //I need to know that the result is successful
         //console.log(res) 
         // I really have no idea what to parse out of the response as it 
         // appears to really give results of the query, which since it was successfull to get 
         // to this point, doesn't really warrant posting the response.
       })
       .on('error', function(err) {
         console.log('Result error: ' + inspect(err));
       })
       .on('end', function(info) {
         /* console.log('Result finished successfully'); */
       });
     } else {
       util.debug(filename+" exists, not updating")
     }
   })
 })
Beispiel #3
0
      renderer[extname.substring(1)]({path: source, text: data._content}, locals, function(err, result){
        if (err) return callback(err);
        if (!layout) return callback(null, result);

        // Relative path
        var layoutPath = pathFn.resolve(source, layout);
        if (!pathFn.extname(layoutPath)) layoutPath += extname;

        var layoutLocals = _.extend({}, locals, {body: result, layout: false});

        fs.exists(layoutPath, function(exist){
          if (exist) return next(null, layoutPath, layoutLocals);

          var viewDir = options.view_dir || options.settings.views;

          if (!exist && !viewDir) return callback(null, result);

          // Absolute path
          var layoutPath = pathFn.join(viewDir, layout);
          if (!pathFn.extname(layoutPath)) layoutPath += extname;

          fs.exists(layoutPath, function(exist){
            if (exist){
              next(null, layoutPath, layoutLocals);
            } else {
              callback(null, result);
            }
          })
        });
      });
Beispiel #4
0
	exports.getIndex = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err) {
						callback('Cant read all indizies');
					} else {
						files.forEach(function(item, index) {
							files[index] = item.replace(/\.json/gm, '');
						});
						callback(false, files);
					}
				});
			} else {
				callback('Database not found!');
			}
		});
	};
Beispiel #5
0
				return function(parallel_fn_callback) {
					var plugin_file = path.join(plugin_dir, plugin_name, 'Index.js');
					Console.debug('Checking plugin file: ' + plugin_file);

					// Check for existence of plugin, if its present - then load it
					// so we can wire up its http routes.
					fs.exists(plugin_file, function(plugin_exists) {
						if(plugin_exists) {
							Console.debug('\nLoaded plugin: ' + plugin_name);
							
							// Load the plugin
							load_plugin(plugin_name, plugin_file, app, parallel_fn_callback);

							// DISABLED CODE // DISABLED CODE // DISABLED CODE // DISABLED CODE
							// Potentially explore auto-restarting the server / plugin as and
							// when it changes. This is probably easiest w/ something like
							// nssm or supervisor for node.
							// // Setup a watch on this plugin so we can reload it
							// var plugin_path = path.join(plugin_dir, plugin_name);
							// fs.watch(plugin_path, function(event, filename) {
							// 	if(filename && filename.match(/^.*\.js$/)) {
							// 		Console.log('Event: ' + event + ' @File: ' + filename);
							// 		load_plugin(plugin_name, plugin_file, app, function(error) {
							// 			console.log(app.routes);
							// 		});
							// 	}
							// });
							// DISABLED CODE // DISABLED CODE // DISABLED CODE // DISABLED CODE
						}
						else parallel_fn_callback();
					});
				};
Beispiel #6
0
i18n.prototype.load = function(path, callback){
  if (typeof callback !== 'function') callback = function(){};

  var render = hexo.render,
    self = this;

  fs.exists(path, function(exist){
    if (!exist) return callback();

    fs.readdir(path, function(err, files){
      if (err) return callback(err);

      async.each(files, function(item, next){
        var extname = pathFn.extname(item),
          name = pathFn.basename(item, extname).toLowerCase().replace(/_/g, '-');

        // Only accepts YAML files
        if (extname !== '.yml' && extname !== '.yaml') return next();

        render.render({path: pathFn.join(path, item)}, function(err, content){
          if (err) return callback(err);

          self.store[name] = content;

          next();
        });
      }, callback);
    });
  });
};
Beispiel #7
0
extend.console.register('new_page', 'Create a new page', function(args){
  if (!args.length){
    console.log('Usage: hexo new_page <title>');
    return false;
  }

  var date = moment().format('YYYY-MM-DD HH:mm:ss'),
    target = hexo.source_dir + args.join('-').toLowerCase() + sep + 'index.md';

  var content = [
    '---',
    'layout: page',
    'title: ' + args.join(' '),
    'date: ' + date,
    'comments: true',
    '---'
  ];

  fs.exists(target, function(exist){
    if (exist){
      console.log('%s already exists. Use other filename instead.', clc.bold(target));
    } else {
      file.write(target, content.join('\n') + '\n', function(err){
        if (err) throw err;
        console.log('Page created at %s', clc.bold(target));
        hexo.emit('newPage', target);
      });
    }
  });
});
Beispiel #8
0
        mkdirp(options.dest, function (err) {
          if (err) throw err;

          var envKey = _.findKey(resultJsons, function () {
            return true;
          });

          var filePath = path.join(options.dest, resultJsons[envKey].filename);

          fsExists(filePath, function (exists) {

            var action;
            if (exists) {
              action = gracefulFs.readFileAsync(filePath, 'utf8')
                .then(function (data) {
                  var newData = resultJsons[envKey].contents;
                  var mergedData = _.merge(JSON.parse(data), newData);
                  return gracefulFs.writeFileAsync(filePath, JSON.stringify(mergedData, null, 2));
                });
            } else {
              var freshData = JSON.stringify(resultJsons[envKey].contents, null, 2);
              action = gracefulFs.writeFileAsync(filePath, freshData);
            }
            action.then(function () {
              self.push(file);
              cb();
            });
          });
        });
Beispiel #9
0
            function(next){
              if (!exist || item.modified) return next(null, true);

              fs.exists(dest, function(exist){
                next(null, !exist);
              });
            },
Beispiel #10
0
    // Set up
    function(next){
      fs.exists(deployDir, function(exist){
        if (exist && !args.setup) return next();

        hexo.log.i('Setting up GitHub deployment...');

        var commands = [
          ['init'],
          ['add', '-A', '.'],
          ['commit', '-m', 'First commit']
        ];

        if (branch !== 'master') commands.push(['branch', '-M', branch]);
        commands.push(['remote', 'add', 'github', url]);

        file.writeFile(path.join(deployDir, 'placeholder'), '', function(err){
          if (err) callback(err);

          async.eachSeries(commands, function(item, next){
            run('git', item, function(code){
              if (code === 0) next();
            });
          }, function(){
            if (!args.setup) next();
          });
        });
      });
    },
Beispiel #11
0
    load_scripts: ['config', function(next, results){
      if (safe || !results.config) return next();

      var dir = baseDir + 'scripts/';

      fs.exists(dir, function(exist){
        if (!exist) return next();
        fs.readdir(dir, function(err, files){
          if (err) throw new Error('Scripts loaded error');

          files.forEach(function(item){
            if (item.substring(0, 1) !== '.'){
              try {
                require(dir + item);
              } catch (err){
                console.log('Script loaded error: %s'.red, item.bold);
                if (debug) throw err;
              }
            }
          });

          next();
        });
      });
    }]
Beispiel #12
0
function find(folder, files, callback) {
    var err;
    var file;

    if (typeof files === 'function') {
        callback = files;
        files = possibleJsons;
    }

    if (!files.length) {
        err = createError('None of ' + possibleJsons.join(', ') + ' were found in ' + folder, 'ENOENT');
        return callback(err);
    }

    file = path.resolve(path.join(folder, files[0]));
    fs.exists(file, function (exists) {
        if (!exists) {
            return find(folder, files.slice(1), callback);
        }

        if (files[0] !== 'component.json') {
            return callback(null, file);
        }

        // If the file is component.json, check it it's a component(1) file
        // If it is, we ignore it and keep searching
        isComponent(file, function (is) {
            if (is) {
                return find(folder, files.slice(1), callback);
            }

            callback(null, file);
        });
    });
}
Beispiel #13
0
 isFileExists: function(filePath) {
     var promise = vow.promise();
     fs.exists(filePath, function(exists) {
         promise[exists ? 'fulfill' : 'reject']();
     });
     return promise;
 },
Beispiel #14
0
var dir = exports.dir = function(source, callback, parent){
  fs.exists(source, function(exist){
    if (exist){
      fs.readdir(source, function(err, files){
        if (err) throw err;

        var result = [];

        async.forEach(files, function(item, next){
          fs.stat(source + '/' + item, function(err, stats){
            if (err) throw err;

            if (stats.isDirectory()){
              dir(source + '/' + item, function(children){
                result = result.concat(children);
                next();
              }, (parent ? parent + '/' : '') + item);
            } else {
              result.push((parent ? parent + '/' : '') + item);
              next();
            }
          });
        }, function(){
          callback(result);
        });
      });
    } else {
      return [];
    }
  });
};
Beispiel #15
0
function ParserList() {
  var self     = this;
  self.parsers = {};

  /**
   * Extract missing domains from domains.miss.csv
   * or generate the file if it does not exist
   */
  fs.exists(missFile, function (exists) {
    if (exists) {
      var firstLine = fs.readFileSync(missFile, 'utf-8').split('\n')[0].trim();
      if (firstLine == 'domain') {
        csvextractor.extract(missFile, function (err, records) {
          records.forEach(function (record) {
            self.addMiss(record.domain);
          });
        });
      } else {
        fs.writeFileSync(missFile, 'domain');
      }
    } else {
      fs.writeFileSync(missFile, 'domain');
    }
  });

  self.missQueue = async.queue(function (domain, callback) {
    fs.appendFile(missFile, '\n' + domain, callback);
  }, 1);
}
Beispiel #16
0
function createLink (srcpath, dstpath, callback) {
  function makeLink (srcpath, dstpath) {
    fs.link(srcpath, dstpath, err => {
      if (err) return callback(err)
      callback(null)
    })
  }

  fs.exists(dstpath, destinationExists => {
    if (destinationExists) return callback(null)
    fs.lstat(srcpath, (err, stat) => {
      if (err) {
        err.message = err.message.replace('lstat', 'ensureLink')
        return callback(err)
      }

      const dir = path.dirname(dstpath)
      fs.exists(dir, dirExists => {
        if (dirExists) return makeLink(srcpath, dstpath)
        mkdir.mkdirs(dir, err => {
          if (err) return callback(err)
          makeLink(srcpath, dstpath)
        })
      })
    })
  })
}
Beispiel #17
0
/**
 * Make the directory if it doesn't exist.
 *
 * @param {string} path to directory.
 * @param {Object} opts optional args.
 *   purge (boolean) - whether or not to purge existing files.
 * @param {Function} callback invoke when done.
 */
function maybeMkdir(path, opts, callback) {
  if (typeof opts === 'function') {
    callback = opts;
    opts = null;
  }

  fs.exists(path, function(exists) {
    if (opts && opts.purge) {
      rimraf.sync(path);
    } else {
      if (exists) {
        return callback && callback();
      }
    }

    (function tryMkdir() {
      fs.mkdir(path, function(err) {
        if (err) {
          // TODO(gaye): Eventually we should give up.
          debug('error maybeMkdir, will try again ' + path + ': ' + err);
          return tryMkdir();
        }

        return callback(null);
      });
    })();
  });
}
Beispiel #18
0
			// 1. Create folder for temp scripts
			function make_temp_dir(next_step) {
				fs.exists(temp_dir, function(exists) {
					if(!exists) {
						fs.mkdir(temp_dir, next_step);
					}
					else next_step();
				});
			},
Beispiel #19
0
        unlock(nm, n, function (er) {
          t.ifError(er, "unlocked path")

          fs.exists(v, function (found) {
            t.notOk(found, "lock deleted OK")
            t.end()
          })
        })
exports.exists = function (filename, callback) {
  if (typeof callback === 'function') {
    return fs.exists(filename, callback)
  }
  return new Promise(resolve => {
    return fs.exists(filename, resolve)
  })
}
Beispiel #21
0
		// Setup the path for the image in case the plugin does
		// not provide an icon
		function setup_source_path(next_step) {
			fs.exists(icon_file, function(exists) {
				if(!exists) {
					icon_file = path.join(__dirname, 'default.png');
				}
				next_step();
			});
		},
Beispiel #22
0
		function makePathIfNone( path, cb ) {
			fs.exists(path, function(exists) {
				if (exists) 
					cb();
				else 
					fs.mkdir( path, [], cb ); 
			});
		}
Beispiel #23
0
 function exists(cb) {
     file = files[idx];
     idx += 1;
     fs.exists(file, function (bool) {
         found = bool;
         cb();
     });
 }
Beispiel #24
0
 build: function() {
     var _this = this,
         promise = Vow.promise();
     try {
         var target = this._target,
             levelList = [],
             levelsToCache = [],
             levelsIndex = {},
             cache = this.node.getNodeCache(target);
         for (var i = 0, l = this._levelConfig.length; i < l; i++) {
             var levelInfo = this._levelConfig[i];
             levelInfo = typeof levelInfo === 'object' ? levelInfo : {path: levelInfo};
             var
                 levelPath = levelInfo.path,
                 levelKey = 'level:' + levelPath;
             if (levelsIndex[levelPath]) continue;
             levelsIndex[levelPath] = true;
             if (!this.node.buildState[levelKey]) {
                 var level = new Level(levelPath, this.node.getLevelNamingScheme(levelPath));
                 if (levelInfo.check === false) {
                     var blocks = cache.get(levelPath);
                     if (blocks) {
                         level.loadFromCache(blocks);
                     } else {
                         levelsToCache.push(level);
                     }
                 }
                 this.node.buildState[levelKey] = level;
             }
             levelList.push(this.node.buildState[levelKey]);
         }
         var pageBlocksPath = this.node.resolvePath('blocks');
         fs.exists(pageBlocksPath, function(res) {
             try {
                 if (res && !levelsIndex[pageBlocksPath]) {
                     levelsIndex[pageBlocksPath] = true;
                     levelList.push(new Level(pageBlocksPath));
                 }
                 return Vow.all(levelList.map(function(level) {
                     return level.load();
                 })).then((function() {
                     levelsToCache.forEach(function(level) {
                         cache.set(level.getPath(), level.getBlocks());
                     });
                     _this.node.resolveTarget(target, new Levels(levelList));
                     return promise.fulfill();
                 }), function(err) {
                     return promise.reject(err);
                 });
             } catch (err) {
                 return promise.reject(err);
             }
         });
     } catch (err) {
         promise.reject(err);
     }
     return promise;
 },
Beispiel #25
0
 function(next){
   fs.exists(pluginDir, function(exist){
     if (exist){
       next();
     } else {
       callback();
     }
   });
 },
Beispiel #26
0
module.exports = function ensureDirectory( directory, callback ){
    fs.exists(directory, function( exists ){
        if( exists ){
            callback();
            return;
        }
        mkdirp( directory, callback);
    });
};
Beispiel #27
0
 function(next){
   fs.exists(configPath, function(exist){
     if (exist){
       next();
     } else {
       callback();
     }
   });
 },
Beispiel #28
0
		// Delete the dst file if its there...
		function delete_destination_image(next_step) {
			fs.exists(dst_file, function(exists) {
				if(exists) {
					Console.log('Deleting file ' + dst_file);
					fs.unlink(dst_file, next_step);
				}
				else next_step();
			});
		},
Beispiel #29
0
// Return a promise resolved with a boolean
function fileExists(filename) {
    var d = Promise.defer();

    fs.exists(filename, function(exists) {
        d.resolve(exists);
    });

    return d.promise;
}
        return (secondaryDepsPromises[parent] = new Promise(function(resolve, reject) {
          if (inject)
            return pkg.inject(parentPkg, resolve).catch(reject);

          fs.exists(pjsonPath, function(exists) {
            if (exists)
              return resolve();
            pkg.download(parentPkg, {}, resolve).then(resolve, reject);
          });
        })