displayDiff() { let info = this, jsdiff = require('diff'); return RSVP.hash({ input: this.render(), output: fs.readFile(info.outputPath), }).then(result => { let diff = jsdiff.createPatch( info.outputPath, result.output.toString().replace(rxEOL, '\n'), result.input.replace(rxEOL, '\n') ); let lines = diff.split('\n'); for (let i = 0; i < lines.length; i++) { info.ui.write( diffHighlight(lines[i] + EOL) ); } }); }
return when.promise(function(resolve) { fs.readFile(path,'utf8',function(err,data) { if (!err) { if (data.length === 0) { log.warn(log._("storage.localfilesystem.empty",{type:type})); try { var backupStat = fs.statSync(backupPath); if (backupStat.size === 0) { // Empty flows, empty backup - return empty flow return resolve(emptyResponse); } // Empty flows, restore backup log.warn(log._("storage.localfilesystem.restore",{path:backupPath,type:type})); fs.copy(backupPath,path,function(backupCopyErr) { if (backupCopyErr) { // Restore backup failed log.warn(log._("storage.localfilesystem.restore-fail",{message:backupCopyErr.toString(),type:type})); resolve([]); } else { // Loop back in to load the restored backup resolve(readFile(path,backupPath,emptyResponse,type)); } }); return; } catch(backupStatErr) { // Empty flow file, no back-up file return resolve(emptyResponse); } } try { return resolve(JSON.parse(data)); } catch(parseErr) { log.warn(log._("storage.localfilesystem.invalid",{type:type})); return resolve(emptyResponse); } } else { if (type === 'flow') { log.info(log._("storage.localfilesystem.create",{type:type})); } resolve(emptyResponse); } }); });
beforeAll(function(done) { expect(fsExtra.readFile(imagePath) .then(function(data) { imageData = data; testGltf = { "images": { "Cesium_Logo_Flat_Low": { "uri": imageUri, "extras": { "_pipeline": { "source": imageData, "extension": '.png' } } } } }; }), done).toResolve(); });
var compile = function(file, project, callback) { var input = path.resolve(project.path, file.input); var output = (file.customOutput) ? path.resolve(project.path, file.customOutput) : $filter('interpolatePath')(file.input, project); var options = { bare: file.config.bare }; fs.readFile(input, 'utf8', function(err, data) { if (err) return callback(new Error('Unable to read source file\n' + err.message)); try { var javascript = livescript.compile(data, options); if (file.config.uglify) { javascript = ugly.minify(javascript, { fromString: true, mangle: file.config.mangle }).code; } fs.outputFile(output, javascript, function(err) { if (err) return callback(new Error('Unable to write compiled data. ' + err.message)); callback(null, input); }); } catch (e) { if (e) return callback(new Error(e.message + '\n' + input)); } }); };
return new Promise(function (resolve, reject) { fs.readFile(targetPath, function (err, bytes) { if (err) { if (err.code === 'ENOENT') { return reject(new common.errors.NotFoundError({ err: err, message: common.i18n.t('errors.errors.imageNotFoundWithRef', {img: options.path}) })); } return reject(new common.errors.GhostError({ err: err, message: common.i18n.t('errors.errors.cannotReadImage', {img: options.path}) })); } resolve(bytes); }); });
function _readFile(username, path, resolve) { function _done(data) { data = data || {}; resolve(username ? (data[username] || []) : data); } _fs.readFile(path, (err, data) => { if ( err ) { _done(null); } else { try { _done(JSON.parse(data)); } catch ( e ) { console.warn('Failed to read', path); _done({}); } } }); }
readObject: function(filePath, callback){ fs.readFile(filePath, {encoding: 'utf8'}, function(err, data){ if(err){ if(callback){ callback(err, null); } } else { try{ if(callback){ callback(null, JSON.parse(data)); } } catch(e){ if(callback){ callback(e, data); } } } }); },
return new Promise((resolve, reject) => { // TODO: Should we support a streaming interface or nah // $FlowFixMe: fs-extra fs.readFile( path.join(options.local.baseDirectory, notebook.path), (err, data) => { if (err) { reject(err); } try { const notebookJSON: Object = JSON.parse(data.toString()); resolve(Object.assign({}, notebook, { content: notebookJSON })); return; } catch (err) { reject(err); } } ); });
/** * Read the build configuration file. * @param {string} configPath Path to config file. * @param {function(Error, Object)} callback Callback. */ function readConfig(configPath, callback) { fs.readFile(configPath, function(err, data) { if (err) { if (err.code === 'ENOENT') { err = new Error('Unable to find config file: ' + configPath); } callback(err); return; } var config; try { config = JSON.parse(String(data)); } catch (err2) { callback(new Error('Trouble parsing config as JSON: ' + err2.message)); return; } callback(null, config); }); }
fs.stat(file, function(err, stats){ if (err) return cb(err); fs.readFile(file, function(err, buffer){ if (err) return cb(err); var file = {}; if (utf8(buffer)) { var parsed = front(buffer.toString()); file = parsed.attributes; file.contents = new Buffer(parsed.body); } else { file.contents = buffer; } file.mode = Mode(stats).toOctal(); file.stats = stats; cb(null, file); }); });
it('removes a tree of objects', function (done) { expect(fsExtra.readFile(gltfPath) .then(function (data) { var gltf = JSON.parse(data); removeAll(gltf); expect(gltf.accessors.accessor_23).not.toBeDefined(); expect(gltf.accessors.animAccessor_0).not.toBeDefined(); expect(gltf.accessors['IBM_Armature_Cylinder-skin']).not.toBeDefined(); expect(gltf.bufferViews.bufferView_30).not.toBeDefined(); expect(gltf.buffers.CesiumTexturedBoxTest).not.toBeDefined(); expect(gltf.cameras.camera_0).not.toBeDefined(); expect(gltf.images.Image0001).not.toBeDefined(); expect(gltf.materials['Effect-Texture']).not.toBeDefined(); expect(gltf.meshes['Geometry-mesh002']).not.toBeDefined(); expect(gltf.nodes['Geometry-mesh002Node']).not.toBeDefined(); expect(gltf.nodes.groupLocator030Node).not.toBeDefined(); expect(gltf.nodes.node_3).not.toBeDefined(); expect(gltf.nodes.txtrLocator026Node).not.toBeDefined(); expect(gltf.programs.program_0).not.toBeDefined(); expect(gltf.samplers.sampler_0).not.toBeDefined(); expect(gltf.shaders.CesiumTexturedBoxTest0FS).not.toBeDefined(); expect(gltf.shaders.CesiumTexturedBoxTest0VS).not.toBeDefined(); expect(gltf.skins['Armature_Cylinder-skin']).not.toBeDefined(); expect(gltf.techniques.technique0).not.toBeDefined(); expect(gltf.textures.texture_Image0001).not.toBeDefined(); expect(Object.keys(gltf.nodes).length).toEqual(0); expect(Object.keys(gltf.skins).length).toEqual(0); expect(Object.keys(gltf.cameras).length).toEqual(0); expect(Object.keys(gltf.meshes).length).toEqual(0); expect(Object.keys(gltf.accessors).length).toEqual(0); expect(Object.keys(gltf.materials).length).toEqual(0); expect(Object.keys(gltf.bufferViews).length).toEqual(0); expect(Object.keys(gltf.techniques).length).toEqual(0); expect(Object.keys(gltf.textures).length).toEqual(0); expect(Object.keys(gltf.buffers).length).toEqual(0); expect(Object.keys(gltf.programs).length).toEqual(0); expect(Object.keys(gltf.images).length).toEqual(0); expect(Object.keys(gltf.samplers).length).toEqual(0); expect(Object.keys(gltf.shaders).length).toEqual(0); }), done).toResolve(); });
gulp.task('create-zip', function(){ fs.readFile('./Config.xml', 'utf8', function (err, data) { if (err) { return console.error(err); } var themeVersion = ''; var pattern = new RegExp(/<theme\s[^>]*?version=\"(.*?)\"/i); var matches = data.match(pattern); if (matches !== null && typeof matches[1] == 'string') { themeVersion = matches[1].trim(); } return gulp.src(['./themes*/community-theme-16*/**', './Config.xml']) .pipe(zip('v' + themeVersion + '-community-theme-16.zip')) .pipe(gulp.dest('./')); }); });
it('should retrieve list contents as an array of text', function(done) { fs.readFile(file, 'utf8', function(err, data) { var flow = [{id:"n1",type:"html",wires:[["n2"]],tag:"ol",ret:"text"}, {id:"n2", type:"helper"}]; helper.load(htmlNode, flow, function() { var n1 = helper.getNode("n1"); var n2 = helper.getNode("n2"); n2.on("input", function(msg) { msg.should.have.property('topic', 'bar'); msg.payload[0].indexOf("Blue").should.be.above(-1); msg.payload[0].indexOf("Red").should.be.above(-1); done(); }); n1.receive({payload:data,topic: "bar"}); }); }); });
it ('should return only the body portion of a post file', function () { var actual; fs.readFile (testFiles + 'post.md', { encoding: 'utf8' }, function (err, input) { if (err) { throw err; } fs.readFile (testFiles + 'post-body.md', { encoding: 'utf8' }, function (err, expected) { if (err) { throw err; } actual = pages.getContent (input); expect (actual).to.equal (expected); }); }); });
app.get('/clean/:page', function (req, res) { var page = req.params.page; var view = getView('clean.html'); fs.readFile(path.join(app.get('user'), 'saved', page + '.html'), "utf8", function(err, data){ if(err) { console.log(err); res.send('No saved data with this id.'); return; } var htmlToSend = mustache.to_html(view, { legoLayer: data, globalOptions: JSON.stringify(opts) }); res.send(htmlToSend); }); });
.then(function readKey() { // Read the public key fs.readFile(filepath + '.pub', { encoding: 'utf-8' }, function(err, pubKey) { if (err) { return reject(err); } // See if the public key is already in the authFile return checkIfKeyInFile(tessel, remoteAuthFile, pubKey) .then(function keyNotInFile() { // Copy pubKey into authFile return copyKey(tessel, remoteAuthFile, pubKey) .then(resolve); }) .catch(reject); }); });
nodeFs.readdir(path, function (err, files) { var folder = new Models.NodeFolder(path); if (!folder.exists) { return; } files.forEach(function (item) { var itemPath = nodeJsPath.join(path, item); try { var stats = nodeFs.statSync(itemPath); if (stats.mode === 33060) return; if (stats.isDirectory() && item[0] !== ".") { folder.folders.push(new Models.NodeFolder(itemPath, folder)); } else if (stats.isFile()) { var extension = nodeJsPath.extname(item); if ((extension === ".md") || (extension === ".html") || (extension === ".htm") || (item === _this.storageService.settings.settingsFilename) || (folder.name === _this.storageService.settings.resourcesFolderName)) { folder.files.push(new Models.NodeDocument(nodeJsPath.join(path, item), folder)); } } } catch (ex) { } }); var settingsFilename = nodeJsPath.join(path, ".notedownSettings"); if (nodeFs.existsSync(settingsFilename)) { nodeFs.readFile(settingsFilename, { encoding: "utf8" }, function (err, data) { if (!err) { try { folder.settings = new Models.FolderSettings(JSON.parse(data)); } catch (ex) { folder.settings = new Models.FolderSettings(); } } }); } resolve(folder); });
export async function extractTemplateApp(starterAppPath: string, name: string, root: string) { Logger.notifications.info({ code: NotificationCode.PROGRESS }, MessageCode.EXTRACTING); await mkdirpAsync(root); await Extract.extractAsync(starterAppPath, root); // Update files Logger.notifications.info({ code: NotificationCode.PROGRESS }, MessageCode.CUSTOMIZING); // Update app.json let appJson = await fs.readFile(path.join(root, 'app.json'), 'utf8'); let customAppJson = appJson .replace(/\"My New Project\"/, `"${name}"`) .replace(/\"my-new-project\"/, `"${name}"`); await fs.writeFile(path.join(root, 'app.json'), customAppJson, 'utf8'); await initGitRepo(root); return root; }
var getRunningPid = function (callback) { Fs.readFile(__dirname + '/scales.pid', { encoding: 'utf-8' }, function (err, text) { if (err) { return callback(err); } try { var pid = parseInt(text); process.kill(parseInt(pid), 0); return callback(undefined, pid); } catch (e) { return callback(e); } }); };
Utils.copyAndModifyFile = function (srcFolder, destFolder, filename, substitutions, next) { // FIXME If this is a directory, we need to recurse into directory! // read in src file, modify contents, write to dest folder fs.readFile(path.join(srcFolder, filename), function (err, data) { var str; if (err) { return next(err); } // Go through each substitution and replace! str = data.toString(); for (var key in substitutions) { if (substitutions.hasOwnProperty(key) ) { str = str.split(key).join(substitutions[key]); } } fs.writeFile(path.join(destFolder, filename), str, next); }); }
async.each(pliers.filesets.pages, function (file, callback) { var dest = file.replace(config.src, config.dest) , ext = path.extname(file) , properties , page = {} fs.readFile(file, 'utf8', function (err, data) { if (err) throw(err) if (frontmatter.test(data)) { properties = frontmatter(data) merge(page, properties.attributes) if (ext === '.md') { page.contents = namp(properties.body).html parseExcerpt(page, properties.body) page.parsed = true } else { page.contents = properties.body } page.path = setDestination(dest, page) page.url = setUrl(page) if (page.date) page.date = moment.utc(page.date) if (page.layout) { parseLayout(page) } pages.push(page) } else { mkdir(path.dirname(dest), function () { fs.copy(file, dest) }) } callback() }) }, function (err) {
function processFile(fileName, extension) { var context, processors; context = getContext(extension); processors = PROCESSORS[extension]; if (processors) { fs.readFile( fileName, function(err, content) { var orignalContent; if (err) { console.log('Cannot read file: ' + fileName + '.\n' + err); return; } content = orignalContent = content.toString(); processors.forEach( function(processor) { content = processor.process(content, context); } ); if (sha1(orignalContent) !== sha1(content)) { fs.writeFile(fileName, content, function(error) { if (error) { console.log(error); } else { console.log('Save: ' + fileName); } }); } } ); } }
ControllerVolsimpleequal.prototype.createASOUNDFile = function() { var self = this; var defer = libQ.defer(); try { fs.readFile(__dirname + "/asound.tmpl", 'utf8', function(err, data) { if (err) { defer.reject(new Error(err)); return console.log(err); } var conf1 = data.replace("${hwout}", self.config.get('alsa_device')); fs.writeFile("/home/volumio/asoundrc", conf1, 'utf8', function(err) { if (err) { defer.reject(new Error(err)); //self.logger.info('Cannot write /etc/asound.conf: '+err) } else { self.logger.info('asound.conf file written'); var mv = execSync('/usr/bin/sudo /bin/mv /home/volumio/asoundrc /etc/asound.conf', { uid: 1000, gid: 1000, encoding: 'utf8' }); var apply = execSync('/usr/sbin/alsactl -L -R nrestore', { uid: 1000, gid: 1000, encoding: 'utf8' }); defer.resolve(); } }); }); } catch (err) {} setTimeout(function() { return defer.promise; }, 2000); };
exports.perms(s, 0, function (r) { // readable? i.readable = r; fs.lstat(file, function (e, ls) { // check if it's a link i.isLink = ls.isSymbolicLink(); if (i.isLink) { fs.readlink(file, function (e, l) { i.link = l; finished(); }); } else { finished(); } }); i.type = s.isDirectory() ? 'directory' : ''; if (!i.type) { // is file if (r && !s.isDirectory() && content) { fs.readFile(file, 'utf8', function (f_e, f) { i.cont = f_e ? null : f; finished(); }); } exports.info.type(file, function (t) { i.type = t; finished(); }); i.size = s.size; } else if (r) { // is dir fs.readdir(file, function (d_e, d) { i.size = s.size; i.items = d_e ? 0 : d.length; finished(); }); } else { i.size = null; i.items = null; if (content) { i.cont = null; } finished(); } finished(); });
async.each(files, (f, cb)=> { fs.readFile(path.join(this.fullpath, f), function (err, data) { if (err) { return cb(err); } else { obj = JSON.parse(data.toString(), reviver); if (filter(obj)) { obj._col = this; obj._delete = function (cb) { this._col.delete(this._id, cb); }; obj._save = function (cb) { this._col.upsert(this, cb); } ret.push(obj); } cb(); } }); }, function (err) {
fs.readFile(pathDest, 'utf8', function (err,data) { if (err) { Logger.error ( err ); return console.log(err); } fs.readFile(pathSrc, 'utf8', function ( err2, data2) { var result = data.replace(phRegex, data2); fs.writeFile(path.sep + pathDest, result, 'utf8', function (err) { if (err) return console.log(err); if ( callback !== null && callback !== undefined ) { callback (); } }); }); });
async function checkNodeVersion(packageName: string): Promise<void> { const packageJsonPath = path.resolve(process.cwd(), 'node_modules', packageName, 'package.json'); const packageJson = JSON.parse(await fse.readFile(packageJsonPath)); if (!packageJson.engines || !packageJson.engines.node) { return; } if (!semver.satisfies(process.version, packageJson.engines.node)) { console.error( chalk.red( 'You are currently running Node %s but create-react-native-app requires %s.' + ' Please use a supported version of Node.\n' ), process.version, packageJson.engines.node ); process.exit(1); } }
, function(req, res) { switch(req.body.login) { case 'Secretaire': fs.readFile( __dirname + '/secretary.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading secretary.html : ', err); } res.writeHead(200); res.write( data.toString() ); res.end(); }); break; default: // Is it a nurse ? res.writeHead(200); res.write("Unsupported login : " + req.body.login); res.end(); } }
const createProject = async options => { const projectFolderName = stripInvalidFilenameCharacters(options.name); const projectPath = path.join(options.path, projectFolderName); const templatePath = `${projectTemplatesRoot}/${options.target}`; const projectDataPath = `${projectPath}/project.json`; if (fs.existsSync(projectPath)) { throw ERR_PROJECT_EXISTS; } await fs.ensureDir(projectPath); await copy(templatePath, projectPath); // Replace placeholders in data file let dataFile = await fs.readFile(projectDataPath, "utf8"); dataFile = dataFile.replace(/___PROJECT_NAME___/g, projectFolderName); await fs.writeFile(projectDataPath, dataFile); return projectDataPath; };
remotepi.prototype.rmBootStr = function() { var self = this; var configFile = "/boot/config.txt"; var searchexp = new RegExp(os.EOL + os.EOL + "*" + lircOverlayBanner + "dtoverlay=.*" + os.EOL + "*"); fs.readFile(configFile, "utf8", function (error, configTxt) { if (error) { self.logger.error("Error reading" + configFile + ": " + error); self.commandRouter.pushToastMessage("error", "RemotePi", "Error reading " + configFile + ": " + error); } else { configTxt = configTxt.replace(searchexp, os.EOL); fs.writeFile(configFile, configTxt, "utf8", function (error) { if (error) { self.logger.error("Error writing" + configFile + ": " + error); self.commandRouter.pushToastMessage("error", "RemotePi", "Error writing " + configFile + ": " + error); } }); } }); };