request('http://localhost:8079/' + targetFile.replace(/^build\//, ''), function(error, response, body) { if (error) { reject(error); return; } if (response.statusCode != 200) { reject(new Error('Status ' + response.statusCode + ':\n' + body)); return; } mkdirp.sync(targetFile.replace(new RegExp('/[^/]*$'), '')); fs.writeFileSync(targetFile, body); resolve(); });
.on('postcopy', function () { gen.end(); if (gen.config.get('rename')) { var folder = gen.config.get('folder'); var component = gen.config.get('component'); fs.renameSync(outputDir + '/index.js', outputDir + '/' + component + '.js'); } console.log(chalk.bgYellow('DONE:'), chalk.yellow('Files have been successfully generated.')); open(outputDir); process.exit(0); })
file_utils.getLocalFile(config.moviepath, movieRequest, function(err, file) { if (err) console.log(err .red); if (file) { var movieUrl = file.href; var stat = fs.statSync(movieUrl); console.log('Client platform is', platform); var movie_playback_handler = require('./movie-playback-handler'); movie_playback_handler.startPlayback(res, movieUrl, stat, platform); } else { console.log("File " + movieRequest + " could not be found!" .red); } });
fs.mkdirp(path.dirname(dest), function(err) { var reader = fs.createReadStream(e.path); reader.on('error', function(err) { err.filename = e.path; done(err); }); var writer = fs.createWriteStream(dest); writer.on('error', function(err) { err.filename = e.path; done(err); }); writer.on('close', function(err) { done(null); }); reader.pipe(writer); });
/* Import a source file, create a file alias for it and save/move them into place */ function import_file_and_make_alias (alias){ // Check that the file is not in the excludes list. if(!ignore_exts[alias.uuid_file_ext]){ console.log('importing ' + alias.uuid ); // Make File Alias const base_dir = base_dir || path.join(__dirname, '../../media') const aliases_dir = path.join( base_dir, '/aliases' , alias.uuid + alias.uuid_file_ext + '.alias' ) fs.writeFile(aliases_dir, JSON.stringify(alias, null, 4), function(err) { if(err) { console.log(err); } else { console.log("Alias created at " + aliases_dir); } }); // Setup File's Directory const target_dir = path.join( base_dir, '/files/', alias.uuid); if (!fs.existsSync(target_dir)) fs.mkdirSync(target_dir); // Import and rename source file. const destination = path.join( target_dir, 'original' + alias.uuid_file_ext ) const source = path.join(source_dir, alias.source_path) fs.move(source, destination, function (err) { if (err) { console.log('File Import: ', err) throw err; } else { console.log("Alias file imported to " + destination); } }); } }
fs.writeFile(sourcefileName, JSON.stringify(config.commandsToRun), function (err) { if (err) console.log(err); else { console.log("File " + sourcefileName + " Created successfully"); config.inFileCounter++; fsextra.copy(sourcefileName, destinationfileName, function (err) { if (err) { next(err, null) console.log(err); } }); } });
fs.readFile(fileName, function(err, data) { if(err) { fs.readFile(fileName, function(err, data) { if(err) { console.error('Error Reading File', err, fileName); defered.resolve(''); } else { finishFunc(data); } }); } else { finishFunc(data); } });
function createZip () { var zip = new Zip() var walker = fse.walk(tmp) walker.on('file', function (root, stat, next) { var dir = path.resolve(root, stat.name) zip.folder(root.substring(tmp.length + 1)).file(stat.name, fs.readFileSync(dir).toString()) next() }) walker.on('end', function () { var data = zip.generate({base64: false, compression: 'DEFLATE'}) fs.writeFileSync(machine + '.zip', data, 'binary') fse.rmrfSync(tmp) }) }
filesArr.forEach(function (file) { file = file.path; fs.readFile(file, 'utf8', function (err, data) { if (!err) { var re = new RegExp(Object.keys(dataMap).join('|'), 'gi'); if (re.toString() !== (/(?:)/gi).toString()) { var result = data.replace(re, function (matched) { return dataMap[matched]; }); fs.writeFileSync(file, result); } } }); });
fs.access(outputDir, function (err) { if (!err) { var contents = fs.readdirSync(outputDir); var length = 0; contents.forEach(function (item) { (item.indexOf('.') !== 0 && item.indexOf('nyg-cfg') === -1) && length++; }); if (length) { console.warn(chalk.bgRed('ERROR:'), chalk.red('Directory ' + outputDir + ' already exists and is not empty.')); gen.end(); } else { gen.chdir(outputDir); (externalPrompts) ? gen.prompt(externalPrompts, done) : done(); } } else { fs.mkdirp(outputDir, function () { console.log(chalk.bgYellow('CREATED DIRECTORY:'), chalk.yellow(outputDir)); gen.chdir(outputDir); (externalPrompts) ? gen.prompt(externalPrompts, done) : done(); }); } });
src.forEach(function(item) { var content; if (item) { content = _fs.readFileSync(item, "utf8"); if (content) { funcs._baseCopy({ content: content, name: name, path: path }); } } });
function crimpIt(pathJSON, cb) { var context = new Context( program, pathJSON ); if (program.clean) { fs.rmrf( path.join( context.testDir, context.tempDir ), (err) => { if (err) throw err; buildProject( context, cb ); }); } else { buildProject( context, cb ); } }
grunt.registerMultiTask('combinations', 'Calculate url combinations from url params', function() { var config = this.data; console.log(config.dest); grunt.verbose.writeln('[log] Scraping data from: ' + config.src + ''); grunt.verbose.writeln('[log] Scraping data to: ' + config.dest); var combinator = new Combinator(config.baseurl, config.params, config); var urls = combinator.combine(); var urlsJson = JSON.stringify(urls); var hasFilename = config.dest.match(/\.([^.]+)$/) !== null; var filename = hasFilename ? config.dest.match(/\/([^\/]+)$/)[1] : this.target; var path = hasFilename ? config.dest.replace(/^(.*\/)[^\/]+$/, '$1') : config.dest; var filepath = path + filename; fs.mkdirRecursiveSync(path); fs.writeFileSync(filename, urlsJson); });
function deleteOldest() { //find the oldest repo var repos = Object.keys(manifest); repos.sort(function(a, b) { return manifest[a] - manifest[b]; }); //the first key is the oldest, if this function is being called, it is garaunteed to exist var repo = repos[0]; fs.rmrf(path.join(config.tmp_dir, repo)); //no callback specified, don't care when this finishes delete manifest[repo]; }
fs.exists("./public/data/", function(dataExists) { if (!dataExists) { fs.mkdirSync("./public/data/"); } fs.exists("./public/data/"+type+"/", function(exists){ if(!exists){ fs.mkdirSync("./public/data/"+type); } fs.exists(outputPath, function(exists){ if(exists){ fs.unlinkSync(outputPath); } if(fs.existsSync(url)){ startTranscoding(mediaID, type, response,url,platform, file, outputPath, ExecConfig); } else{ console.log('File '+ url + 'not found, did you move or delete it?'); } }); }); });
function attach_tgz(tgz_name, doc, callback) { fs.readFile(tgz_name, function (err, content) { if (err) return callback(err); if (!doc._attachments) { doc._attachments = {}; } doc._attachments[tgz_name] = { 'content_type': 'application/octet-stream', 'data': content.toString('base64') }; callback(null, doc); }); }
WordMachine.prototype.randText = function(callback) { var self = this; var textFile = path.resolve(_.sample(self.textFiles)); self.logger.debug("Opening file: "+textFile); var fd = fs.createReadStream(textFile); var data = "", error = null; fd.on("readable", function() { self.logger.debug("Reading file: "+textFile); }); fd.on("data", function(chunk) { data += chunk; }); fd.on("error", function(err) { error = err; }); fd.on("end", function() { callback(error, data); }); };
bot.startConversation(message, function (err, convo) { convo.say('I heard that you need help.'); helpTopics = 'Here are the topics I can help you with:\n'; var files = fs.readdirSync(path.resolve(process.cwd(), 'skills')); var files = files.map(function (file) { return '`' + file.split('.')[0] + '`'; }); helpTopics += files.join(', '); helpTopics += ', `general`' helpTopics += '.'; convo.say(helpTopics); convo.ask('Which of those do you want help with? Or enter `done` to finish with help.', responses); convo.next(); });
var renderThis = function(filePath, options, callback) { fs.readFile(filePath, 'ascii' , function(err, data) { if (err) { callback(err); return; } var file = ejs.render(data, options); //Write output fs.writeFile(filePath, file, 'ascii' , function(err) { if(err) { callback(err); } else { callback(null, "Done"); } }); }); };
moveFile(file.type, tmp_path, target_path, function(err) { if (err) { return cb(err); } fs.exists(tmp_path, function(exists) { if (exists) { fs.unlink(tmp_path, function(err) { if (err) { return cb(err); } }); } }); if (file.isImage || file.isVideo) { gm(target_path) .size(function (err, data) { if (err) { return cb(err); } file.dimensions = data; file.save(function(err, file) { if(err) { return cb(err); } file.generateStandardThumbnails(function(err) { if(err) { return cb(err); } cb(null, file); }); }); }); } else { file.save(function(err, file) { if (err) { return cb(err); } cb(null, file); }); } });
(function () { 'use strict'; var CStore = require('node-cstore') , CSModel = CStore.CSModel , logger = require('../util').logger , fs = require('fs.extra') , path = require('path') , ipc = require('ipc'); var AppStore = new CStore({ name: 'app-store', filename: path.resolve(process.cwd(), 'data', 'app-data.json') }); if (fs.existsSync(AppStore.config.getValue('filename'))) { AppStore.load(); } var SeriesModel = AppStore.getModel('series'); if (!SeriesModel) { AppStore.addModel(new CSModel({name: 'series'})); SeriesModel = AppStore.getModel('series'); } SeriesModel.on('change', function (data) { logger.info('count series stored in database:', data.length); AppStore.save(); }); SeriesModel.update({state: {'$eq': 'new'}}, {state: null}); var LangModel = AppStore.getModel('lang'); if (!LangModel) { AppStore.addModel(new CSModel({name: 'lang'})); LangModel = AppStore.getModel('lang'); } LangModel.on('change', function (data) { logger.info('updated languages'); AppStore.save(); }); _.forEach(ipc.sendSync('get-languages'), function (language) { LangModel.insertOrUpdate({id: {'$eq': language.id}}, language); }); module.exports = AppStore; }());
var download = function(done) { currentJob.saveStatus(1); var _tempPath = path.join(__dirname, 'tmp', 'temp.psd'); //Uncomment the following code to download file from filepicker.io instead of using local file var _fileStream = fs.createWriteStream(_tempPath); _fileStream.on('error', function (err) { done(err); }); _fileStream.on('close', function(){ done(null, _tempPath); }); request(currentJob.url).pipe(_fileStream); // done(null, _tempPath); };
function compress() { console.log('Compressing...'); process.chdir(__dirname); if (!fs.existsSync(exeFile)) { console.error('File doesn\'t exist: ' + exeFile); process.exit(1); } if (fs.existsSync(targetFile)) { fs.unlinkSync(targetFile); } if (process.platform === 'win32') { run(upxPath, ['-9', '--lzma', '-v', '-o' + targetFile, exeFile], function() { complete(); }); } else { //fs.writeFileSync(targetFile, fs.readFileSync(exeFile));fs.chmodSync(targetFile, 0x777);complete();return; run('strip', ['-x', exeFile], function() { run(upxPath, ['-9', '--lzma', '-v', '-o' + targetFile, exeFile], function() { fs.chmodSync(targetFile, 0x777); complete(); }); }); } }
gulp.task('assets', function(){ gulp.src('src/index.html') .pipe($.usemin({ css: [$.minifyCss(), 'concat'], js: [$.uglify(), 'concat'] })) .pipe(gulp.dest('dist')); gulp.src('src/vendor/font-awesome/fonts/*') .pipe(gulp.dest('dist/fonts')) fs.copyRecursive('data', './dist/data', function (err) { if (err) { throw err; } }); });
_copySync = function (source, target, cb) { var cbCalled = false, me = this, rd, wr; if (!_fs.existsSync(source)) { return undefined; } rd = _fs.createReadStream(source); rd.on("error", function (err) { done(err); }); wr = _fs.createWriteStream(target); wr.on("error", function (err) { done(err); }); wr.on("close", function (ex) { done(); }); rd.pipe(wr); function done(err) { if (!cbCalled) { if (err) { throw err; } if (cb) { cb(err); } cbCalled = true; } } };
exports.storeObjectAs = function storeObjectAs(object, filepath, callback) { if(typeof(callback) !== 'function') callback = function(){}; var serialized; try { serialized = exports.serializeObject(object); fs.writeFile(filepath, serialized, function(err){ callback(err, serialized); }); } catch(e){ callback(e); } };
fs.copy($scope.jsonURL, newPath, { replace: false }, function (err) { if (err) { throw err; } console.log("JSON backuped as:", newPath); // save var json = JSON.stringify($scope.allGames, null, 4); fs.writeFile($scope.jsonURL, json, function (err) { if (err) return console.log(err); console.log('JSON saved!'); $scope.$apply(function(){ $scope.noNeedToSave = true; } ); }); });
// Can take any file or directory and upload it to a bucket on // Amazon S3, but we only use this function for uploading // individual files. Why? Again, memory leaks. We can't really // predict how big a directory is going to be, but we know that // it will be larger than a single file. function uploadToS3 (compressed, s3Bucket, callback) { aws.config.loadFromPath("./awsConfig.json"); var s3 = new aws.S3({params: {Bucket: s3Bucket}}); fs.readFile(compressed, function (err, res) { if (err) callback(err); else { var s3Path = compressed.split("/outputs/records/")[1]; var data = {Key: String(s3Path), Body: res}; s3.putObject(data, function (err, data) { if (err) callback(err); else callback(data); }) } }) }
fs.stat(newFilePath, function (err, stat) { if (typeof stat === "undefined") { // File does not exist already, so move it in to place fs.move(file.path, newFilePath, function (err) { if (err) { throw err; } }); } else { } addSHA1ToMetadata(fileId, file.sha1checksum); });
fs.exists(cordovaLibPath, function (cordovaLibPathExists) { if (!cordovaLibPathExists && build.conf.androidreleaseapk) { var source = build.conf[build.conf.buildmode == 'release' ? 'androidreleaseapk': 'androiddebugapk']; var dest = path.resolve(androidFolder, path.basename(source)); fs.copy(source, dest, function(err) { if (build.conf.status === 'cancelled') return; if (err) return agent.buildFailed(build, 'Error copying apk {2} to {3}\n{4}', source, dest, err); apkGlobPath = [dest]; updateAssetsWWW = true; agent.log(build, Msg.info, "Apk found {2}. Updating only assets/www for a faster build", apkGlobPath[0]); ensureAssetsFolder("cordova prepare {0} {1}"); }); } else ensureAssetsFolder(); });