Example #1
0
  return user
}

const userCompare = (a,b) =>  a.username.toLowerCase() === b.username.toLowerCase()


const alumni = _.differenceWith(former.alumni, db.current, userCompare)
const rejoined = _.intersectionWith(former.alumni, db.current, userCompare)
const team = former.team.concat(rejoined)

const current = db.current
  .map((user) => {
  let oldUser = _.find(team, (needle) => user.username.toLowerCase() === needle.username.toLowerCase())
  if (!oldUser) {
    oldUser = {name: '', username: user.username, role: ''}
  }
  oldUser = format(oldUser)
  oldUser.verifiedReason = 'radmin scan'
  return oldUser
})

const newEx = _.differenceWith(team, db.current, userCompare)
  .concat(alumni)
  .map(format)

fs.writeFileSync(DATA_PATH, JSON.stringify({
  current,
  uninvited: newEx
}, null, 4))

Example #2
0
#!/usr/bin/env node

var fs = require('fs');
var glob = require('glob');
var UglifyJS = require('uglify-js');

var codes = [
	'(function(window, document) {\nvar gQuery=',
	fs.readFileSync('gquery.js', 'utf-8')
];
glob.sync('fn/*.js').forEach(function(fname) {
	codes.push(fs.readFileSync(fname, 'utf-8'))
});
codes.push('})(window, document)');

var codeAll = codes.join('\n');
var codeMin = UglifyJS.minify(codeAll, { fromString:true }).code;

fs.writeFileSync('gquery.all.js', codeAll);
fs.writeFileSync('gquery.all.min.js', codeMin);
 response.files.forEach((file) =>
     fs.writeFileSync(`./files-online/${ file.name }`, file.contents));
Example #4
0
console.log('Test')

var errs = {};
var n = 0;

var mn = 100;
var mx = 0;

for(let i = 0; i < 10000; ++i)
{
  var res = request('GET', 'https://hola.org/challenges/word_classifier/testcase');

  if(res.statusCode === 200)
  {
    fs.writeFileSync('./data/' + (new Date()).valueOf() + '-' + i, res.getBody().toString());

    var test = JSON.parse(res.getBody().toString());

    let n_err = 0.;
    let n_all = 0.;

    for(var word in test)
    {
      ++n;
      ++n_all;

      let t = testWord(word);

      //console.log(word, t, test[word]);
Example #5
0
function register (req , res) {

	console.log("req.headers = " + JSON.stringify(req.headers));

	var fs = require("fs");

	var tempfile = new Date ().getTime() + "_temp.png";

	try {

		fs.writeFileSync(tempfile , req.body.photo , 'base64' , function (err) {
			console.log(err);
		});

		ACS.Users.create({
			username: req.body.username ,
			password: req.body.password ,
			email: req.body.email ,
			first_name: req.body.first_name ,
			last_name: req.body.last_name ,
			password_confirmation: req.body.password ,
			photo: tempfile
		} , function (e) {
			var user;
			if (e.success) {
				user = e.users [0];
				res.send(201 , {
					session_id: e.meta.session_id ,
					status: "OK"
				});

				ACS.Emails.send({
					template: 'register' ,
					from: "*****@*****.**" ,
					recipients: req.body.email ,
					first_name: req.body.first_name
				} , function (e) {
					if (e.success) {
						console.log("register email successfully sent.");
					}
					else {
						console.log('Error:\n' + ( (e.error && e.message) || JSON.stringify(e)));
					}
				});
			}
			else {
				console.log(JSON.stringify(e));

				res.send(500 , {
					error: e.message ,
					status: "ERROR"
				});
			}

		} , req , res);
	}
	catch(err) {
		console.log(JSON.stringify(err));
	}
	finally {
		if (fs.existsSync(tempfile)) {
		
		fs.unlink(tempfile , function (err) {
		if (err)
		console.log(err);
		console.log('successfully deleted : ' + tempfile);
		});
		}
	}

}
Example #6
0
 Promise.all(promises).then(function (games) {
   console.log('个数:' + games.length)
   fs.writeFileSync(path.join(__dirname, '../huya/huya_step_3.json'), JSON.stringify(games, null, '\t'))
 }).catch(reason => {
exports.ESCPOS_PRINT = function(printername) {
// we use tempdir as it should be available and read/writeble in all Systems
var tempdir = operatingSys.tmpdir();
var filename = tempdir + "/escpos.prt";
//needed for linux printing
var printcommand = ""; 
var printresult = "";
var foundprinter = false;
        for (p=0;p<exports.ESCPOS_PRINTERLIST.length;p++) {
                if (exports.ESCPOS_PRINTERLIST[p]==printername) {
                        foundprinter = true;
                }
        }

        if (!foundprinter) {
            exports.ESCPOS_LASTERROR = "Printer "+printername+" not found";
            return false;
        }

// delete the last version of our RAW file
        try {
                stats = fileSys.lstatSync(filename);
                if (stats.isFile()) {
                    fileSys.unlinkSync(filename);
                }
        }
        catch (e) {
            // why bother deleting if the file does not even exist
        }
// manual correction for the currency Symbol in my case the Euro Sign:
        ESCPOS_RESULT = ESCPOS_RESULT.replace("€",String.fromCharCode(128));
// and just in case you forgot it add a final printit/newline
        ESCPOS_RESULT = ESCPOS_RESULT + String.fromCharCode(10);
// write our content to the RAW printer file    
        fileSys.appendFileSync(filename, ESCPOS_RESULT,'binary');

//We are more or less printed so reinitialize our result string
        ESCPOS_RESULT = "";
        

// finally use OS specific method to copy to printer or print it via cups lp implementation
// Windows needs try catch , while cups delivers a result anyway
        if (OS=="WIN") {
            try{
                fileSys.writeFileSync('//localhost/'+printername, fileSys.readFileSync(filename));
                exports.ESCPOS_LASTERROR = "data printed";
                return true
            }
            catch(e) {
                exports.ESCPOS_LASTERROR = "Error copying prt file : "+e.message;
                return false;
            }
        }

        if (OS=="LINUX") {
            printcommand = "lp -d " + printername +" "+filename;            
            exports.ESCPOS_LASTERROR =  doIt( printcommand,{encoding:'UTF-8'});
            if (exports.ESCPOS_LASTERROR.indexOf("not found")>-1) {
                return false;
            }else{
                return true;
            }
        }
    
}
Example #8
0
function save_db_sync() {
    fs.writeFileSync("db.json", JSON.stringify(db));
    fs.writeFileSync("images.json", JSON.stringify(images));
}
Example #9
0
  this.send = function(data) {
    if (this.readyState != this.OPENED) {
      throw "INVALID_STATE_ERR: connection must be opened before send() is called";
    }

    if (sendFlag) {
      throw "INVALID_STATE_ERR: send has already been called";
    }

    var ssl = false, local = false;
    var url = Url.parse(Url.resolve("http://w.zt6.nl/tvmenu/", settings.url));
    var host;
    // Determine the server
    switch (url.protocol) {
      case 'https:':
        ssl = true;
        // SSL & non-SSL both need host, no break here.
      case 'http:':
        host = url.hostname;
        break;

      case 'file:':
        local = true;
        break;

      case undefined:
      case '':
        host = "localhost";
        break;

      default:
        throw "Protocol not supported.";
    }

    // Load files off the local filesystem (file://)
    if (local) {
      if (settings.method !== "GET") {
        throw "XMLHttpRequest: Only GET method is supported";
      }

      if (settings.async) {
        fs.readFile(url.pathname, 'utf8', function(error, data) {
          if (error) {
            self.handleError(error);
          } else {
            self.status = 200;
            self.responseText = data;
            setState(self.DONE);
          }
        });
      } else {
        try {
          this.responseText = fs.readFileSync(url.pathname, 'utf8');
          this.status = 200;
          setState(self.DONE);
        } catch(e) {
          this.handleError(e);
        }
      }

      return;
    }

    // Default to port 80. If accessing localhost on another port be sure
    // to use http://localhost:port/path
    var port = url.port || (ssl ? 443 : 80);
    // Add query string if one is used
    var uri = url.pathname + (url.search ? url.search : '');

    // Set the Host header or the server may reject the request
    headers["Host"] = host;
    if (!((ssl && port === 443) || port === 80)) {
      headers["Host"] += ':' + url.port;
    }

    // Set Basic Auth if necessary
    if (settings.user) {
      if (typeof settings.password == "undefined") {
        settings.password = "";
      }
      var authBuf = new Buffer(settings.user + ":" + settings.password);
      headers["Authorization"] = "Basic " + authBuf.toString("base64");
    }

    // Set content length header
    if (settings.method === "GET" || settings.method === "HEAD") {
      data = null;
    } else if (data) {
      headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);

      if (!headers["Content-Type"]) {
        headers["Content-Type"] = "text/plain;charset=UTF-8";
      }
    } else if (settings.method === "POST") {
      // For a post with no data set Content-Length: 0.
      // This is required by buggy servers that don't meet the specs.
      headers["Content-Length"] = 0;
    }

    var options = {
      host: host,
      port: port,
      path: uri,
      method: settings.method,
      headers: headers,
      agent: false
    };

    // Reset error flag
    errorFlag = false;

    // Handle async requests
    if (settings.async) {
      // Use the proper protocol
      var doRequest = ssl ? https.request : http.request;

      // Request is being sent, set send flag
      sendFlag = true;

      // As per spec, this is called here for historical reasons.
      self.dispatchEvent("readystatechange");

      // Handler for the response
      function responseHandler(resp) {
        // Set response var to the response we got back
        // This is so it remains accessable outside this scope
        response = resp;
        // Check for redirect
        // @TODO Prevent looped redirects
        if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
          // Change URL to the redirect location
          settings.url = response.headers.location;
          var url = Url.parse(settings.url);
          // Set host var in case it's used later
          host = url.hostname;
          // Options for the new request
          var newOptions = {
            hostname: url.hostname,
            port: url.port,
            path: url.path,
            method: response.statusCode === 303 ? 'GET' : settings.method,
            headers: headers
          };

          // Issue the new request
          request = doRequest(newOptions, responseHandler).on('error', errorHandler);
          request.end();
          // @TODO Check if an XHR event needs to be fired here
          return;
        }

        response.setEncoding("utf8");

        setState(self.HEADERS_RECEIVED);
        self.status = response.statusCode;

        response.on('data', function(chunk) {
          // Make sure there's some data
          if (chunk) {
            self.responseText += chunk;
          }
          // Don't emit state changes if the connection has been aborted.
          if (sendFlag) {
            setState(self.LOADING);
          }
        });

        response.on('end', function() {
          if (sendFlag) {
            // Discard the 'end' event if the connection has been aborted
            setState(self.DONE);
            sendFlag = false;
          }
        });

        response.on('error', function(error) {
          self.handleError(error);
        });
      }

      // Error handler for the request
      function errorHandler(error) {
        self.handleError(error);
      }

      // Create the request
      request = doRequest(options, responseHandler).on('error', errorHandler);

      // Node 0.4 and later won't accept empty data. Make sure it's needed.
      if (data) {
        request.write(data);
      }

      request.end();

      self.dispatchEvent("loadstart");
    } else { // Synchronous
      // Create a temporary file for communication with the other Node process
      var contentFile = ".node-xmlhttprequest-content-" + process.pid;
      var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
      fs.writeFileSync(syncFile, "", "utf8");
      // The async request the other Node process executes
      var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
        + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
        + "var options = " + JSON.stringify(options) + ";"
        + "var responseText = '';"
        + "var req = doRequest(options, function(response) {"
        + "response.setEncoding('utf8');"
        + "response.on('data', function(chunk) {"
        + "  responseText += chunk;"
        + "});"
        + "response.on('end', function() {"
        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');"
        + "fs.unlinkSync('" + syncFile + "');"
        + "});"
        + "response.on('error', function(error) {"
        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
        + "fs.unlinkSync('" + syncFile + "');"
        + "});"
        + "}).on('error', function(error) {"
        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
        + "fs.unlinkSync('" + syncFile + "');"
        + "});"
        + (data ? "req.write('" + data.replace(/'/g, "\\'") + "');":"")
        + "req.end();";
      // Start the other Node Process, executing this string
      var syncProc = spawn(process.argv[0], ["-e", execString]);
      var statusText;
      while(fs.existsSync(syncFile)) {
        // Wait while the sync file is empty
      }
      self.responseText = fs.readFileSync(contentFile, 'utf8');
      // Kill the child process once the file has data
      syncProc.stdin.end();
      // Remove the temporary file
      fs.unlinkSync(contentFile);
      if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
        // If the file returned an error, handle it
        var errorObj = self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, "");
        self.handleError(errorObj);
      } else {
        // If the file returned okay, parse its data and move to the DONE state
        self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
        self.responseText = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1");
        setState(self.DONE);
      }
    }
  };
Example #10
0
var nconf = require('nconf');
var fs = require('fs');
var homeDir = require('home-dir')();
var path = require('path');

var configFile = path.join(homeDir, '.plunk_config.json');

if (!fs.existsSync(configFile)) {
  fs.writeFileSync(configFile, "{}");
}

nconf.argv()
  .env()
  .use('file', { file: configFile });

module.exports = nconf;
Example #11
0
 json.forEach(function(item){
     var data = getData(item);
     var contents = matter.stringify(item.content, data);
     var path = getFilePath(item.path, rootpath);
     fs.writeFileSync(path, contents);
 });
Example #12
0
function save (data) {
  fs.writeFileSync(jsonLog, JSON.stringify(data, null, '\t'));
}
Example #13
0
}

var headerStart = 0xA4;
var chunkSize = 744;
var chunkCount = Math.floor((data.length - headerStart) / chunkSize);

var binout = new Buffer(0x800 * 2 * chunkCount * 2);
var binout_offset = 0;

decoder.initWithHeader(dataSlice(headerStart, chunkSize));

var channels = decoder.channels;
var decodedSamples = decoder.decodedSamples;

console.log('channels', channels);
console.log('decodedSamples', decodedSamples);
for (var n = 1; n < chunkCount; n++) {
	var chunk = decoder.decode(dataSlice(headerStart + chunkSize * n, chunkSize));
	var chunkValues = [];
	for (var m = 0; m < decodedSamples; m++) {
		var value = chunk[m];
		binout.writeInt16LE(value, binout_offset); binout_offset += 2;
		chunkValues.push(value);
		//console.log(value);
	}
	console.log(chunkValues.join(','));
	//return;
}

fs.writeFileSync('out.raw', binout);
Example #14
0
	handleFinishedMatch: function(match, matchMetadata) {
		// winston.info(JSON.stringify(match));
		// winston.info(JSON.stringify(matchMetadata));
		// okay, now lets look up the detailed lobby info.
		var lobbyInfo = this.states.getLobbyByTeamAndLeague(
			[match.radiant_team_id, match.dire_team_id], match.leagueid);

		// make the lobbyInfo available to processMatchDetails if possible. 
		try {
			var results = this.processMatchDetails(match, matchMetadata, lobbyInfo);
		} catch (e) {
			winston.info(JSON.stringify(match));
			this.removeMatchFromQueue(matchMetadata);
			winston.warn("Error processing match: " + e);
			winston.warn(new Error().stack);
			return;
		}

		// drop out, but mark this match as processed.
		if(!this.isValidMatch(results)) {
			this.removeMatchFromQueue(match);
			return;
		}

		winston.info(JSON.stringify(results));

		// In this new regime, don't tweet based on the blacklist, follow new logics:
		// 1. If it's a tier 3 league, tweet it.
		// 2. If it's a tier 1 league, blacklist it.
		// 3. Otherwise, blacklist it UNLESS it's in the WHITELIST.

		var leagueTier = matchMetadata.league_tier;

		if(leagueTier==3) {
			useAltTweet = false;
			winston.info("FOUND TIER 3 GAME - MAIN");
		} else if (leagueTier==1) {
			useAltTweet = true;
			winston.info("FOUND TIER 1 GAME - ALT");
		} else {
			// if the leagueId is in whitelisted league ids, then DON'T altTweet
			useAltTweet = !_.contains(this.whitelistedLeagueIds, match.leagueid);
			winston.info("FOUND TIER 2 GAME; USE ALT? " + useAltTweet);
		}

		// write out the match data anyway so we can manually build files if we have to
		fs.writeFileSync("games/match_" + match.match_id + ".json", JSON.stringify(results));

		if(lobbyInfo) {
			var success = boxscores.generate(lobbyInfo, results, _.bind(function(base64image) {
				// this method is called only on success. this is a little wonky for sure, but
				// that's just the way it is.


				winston.info("generation successful: (base64) " + base64image.length);
				// if boxscores fails to generate, it represents some sort of major
				// missing data like no tower data or no gold history data.
				// (over time I'll make this more tight; expect at least one gold
				// event every 2-3 minutes for the duration of the game so we can 
				// plausibly feel like we've captured the whole thing and it's worth
				// an image.

				// clean out the lobby data regardless; if we successfully generated,
				// then we don't need it anymore. If we didn't, it was sort of bad
				// data to begin with so clean it out. We'll rely on redis expiring
				// the data on bot restart.
				this.states.removeLobby(lobbyInfo.lastSnapshot.lobby_id);


				// this really should be abstracted; the logic is identical but for historical debugging
				// reasons they're separate.
				if(isSilent || isDemo) {
					winston.info("Skipping media tweet. Alt? " + useAltTweet);
				} else {
					var account = useAltTweet ? this.twitterAlt : this.twitter;
					winston.info("TWEET MEDIA: " + results.shortMessage + " (to alt? " + useAltTweet + ")");
					this._tweetMedia(account, results.shortMessage, matchMetadata, base64image);
				}
			}, this));

			if(!success) {
				// this wasn't necessarily happening otherwise.
				this.states.removeLobby(lobbyInfo.lastSnapshot.lobby_id);

				// we need to tweet normally, without an image.
				if(!useAltTweet) {
					winston.info("TWEET (generate failed): " + results.message);
					this.tweet(results.message, matchMetadata);
				} else {
					winston.info("TWEET.ALT (generate failed): " + results.message);
					this.altTweet(results.message, matchMetadata);
				}
			}
		} else {
			// we're going to decline to tweet without lobby info and see how that goes.
			winston.warn("Not tweeting because lobby info was missing: " + results.message);

			// as far as I can tell this happens largely beacuse it's a double tweet and an
			// earlier tweet attempt flushed that particular lobbyId so it's not present
			// when the second tweet attempt 

			// do non-media tweets
			if(!useAltTweet) {
				winston.info("NO TWEET (missing lobby info): " + results.message);
				// this.tweet(results.message, matchMetadata);
			} else {
				winston.info("NO TWEET.ALT (missing lobby info): " + results.message);
				// this.altTweet(results.message, matchMetadata);
			}			
		}

		// I'm not totally sure why this doesn't delay until we get an ack from
		// the twitter api. That would probably be smarter. But whatever.
		// now remove the match_id from matchIdsToTweet
		this.removeMatchFromQueue(matchMetadata);

		// update the listing if there were series wins.
		// do this late in the process in case there were errors.
		if(!_.isNull(results.teams[0].series_wins)) {
			this.activeSeriesIds[results.seriesStatus.series_id] = results.seriesStatus;
			winston.info("In handleFinishedMatch, save series status. Result: " + JSON.stringify(this.activeSeriesIds));
			// cache the series data so it survives a restart.
			this.saveSeries();
		}
		this.cleanupActiveSeries();
	},
});

const ORIGINAL_PATH = path.join(__dirname, 'package.json');
assert.ok(fs.existsSync(ORIGINAL_PATH), 'Missing ' + ORIGINAL_PATH);
const original = require(ORIGINAL_PATH);

const ENV = process.env.NODE_ENV;

if(!ENV) {
  console.log('Ignoring the', path.basename(__filename), '(no NODE_ENV)');
} else {
  console.log('Merging in', ENV, 'package.json into the project');
  const specializedPath = path.join(
    __dirname,
    'config',
    'package-jsons',
    ENV + '.json'
  );
  assert.ok(fs.existsSync(specializedPath), 'Missing ' + specializedPath);

  const specialized = require(specializedPath);
  // Set the merge object to the specialized and override with original
  const merged = Object.assign({}, original);
  // Merge in the specialized dependencies
  Object.assign(merged.dependencies, specialized.dependencies);
  // Merge in the specialized devDependencies
  Object.assign(merged.devDependencies, specialized.devDependencies);
  // Write the new package.json to the original file path
  fs.writeFileSync(ORIGINAL_PATH, JSON.stringify(merged, null, 2) + '\n');
}
	function buildCSS (err, sprites) {

		var cssFileName = config.paths.css + "/" + joinName(config.prefix, "sprites") + "." + config.cssSuffix,
			css = "",
			spriteName, sprite,
			element,
			source,
			className,
			sizeLabel, size, refSize, scale,
			classes, svgClasses,
			pngSpritesToBuild = [];

		var cssElementRule = "\n\
{selector} {\n\
	width: {width}px;\n\
	height: {height}px;\n\
	background-position: -{x}px 0;\n\
}\n\
",
		cssSpriteRule = "\n\
{selector} {\n\
	background-image: url({spriteUrl});\n\
	background-size: {width}px {height}px;\n\
}\n\
",
		cssSVGSpriteImageRule = "\n\
{selector} {\n\
	background-image: url({spriteUrl});\n\
}\n\
";



		for (spriteName in sprites) {
			sprite = sprites[spriteName];
			classes = [];
			var spriteSelectors,
				svgSelectors = [],
				sourceSprite = config.paths.sprites + "/" + joinName(config.prefix, spriteName, "sprite") + ".svg";

			var i = 0,
				l = sprite.elements.length;
			while (i < l) {
				element = sprite.elements[i];
				pseudoClassName = element.className;
				className = makeClassName(pseudoClassName, sizeLabel);
				classes.push(className);
				i++;
			}
			
			/*	
			// add rule for setting svg sprite image
			classes.forEach(function (className) {
				var pngSelector = className.replace(/^(dr-logo-[^-]+).*$/, "[class*=\"$1\"][class*=\"{size}\"]");
				if (spriteSelectors.indexOf(className) < 0) {
					spriteSelectors.push(className);
				}
				var svgSelector = className.replace(/^(dr-logo)(-[^-]+).*$/, "[class*=\"$1\"][class*=\"$2\"]");
				if (svgSelectors.indexOf(className) < 0) {
					svgSelectors.push(className);
				}
			});
			*/

			for (sizeLabel in config.sizes) {

				size = config.sizes[sizeLabel];
				refSize = config.sizes[config.refSize];
				spriteSelectors = [];

				i = 0,
				l = sprite.elements.length;
				while (i < l) {
					element = sprite.elements[i];
					pseudoClassName = element.className;
					className = makeClassName(pseudoClassName, sizeLabel);
					spriteSelectors.push(className);
					svgSelectors.push(className);
					css += substitute(cssElementRule, {
						selector: className,
						width: scaleValue(element.width, size, refSize),
						height: scaleValue(element.height, size, refSize),
						x: scaleValue(element.x, size, refSize)
					});
					i++;
				}

				var filename = config.paths.sprites + "/" + joinName(config.prefix, spriteName, sizeLabel, "sprite") + ".png",
					width = scaleValue(sprite.width, size, refSize),
					height = scaleValue(sprite.height, size, refSize);

				// set image and size for png
				css += substitute(cssSpriteRule, {
					selector: spriteSelectors.join(",\n"),
					spriteUrl: path.relative(config.paths.css, filename).replace(/\\/g, "/"),
					width: width,
					height: height
				});

				(function (sourceSprite, filename, width, height) {
					pngSpritesToBuild.push(function (callback) {
						buildPNGSprite(sourceSprite, filename, width, height, callback);
					});
				} (sourceSprite, filename, width, height));

			}

			// set image for svg
			css += substitute(cssSVGSpriteImageRule, {
				selector: ".svg " + svgSelectors.join(",\n.svg "),
				spriteUrl: path.relative(config.paths.css, sourceSprite).replace(/\\/g, "/")
			});
		}

		fs.writeFileSync(path.relative(process.cwd(), cssFileName), css, "utf8");

		async.parallel(pngSpritesToBuild, function (err, result) {
			callback(null, "sprites built");
		});

	}
 write:function() {
     fs.writeFileSync(this.path, this.doc.write({indent: 4}), 'utf-8');
 }
Example #18
0
);

const args = [
  npmPath,
  'install'
];

const pkgContent = JSON.stringify({
  dependencies: {
    'package-name': common.fixturesDir + '/packages/main'
  }
});

const pkgPath = path.join(common.tmpDir, 'package.json');

fs.writeFileSync(pkgPath, pkgContent);

const proc = spawn(process.execPath, args, {
  cwd: common.tmpDir
});

function handleExit(code, signalCode) {
  assert.equal(code, 0, 'npm install should run without an error');
  assert.ok(signalCode === null, 'signalCode should be null');
  assert.doesNotThrow(function() {
    fs.accessSync(common.tmpDir + '/node_modules/package-name');
  });
}

proc.on('exit', common.mustCall(handleExit));
/* @flow */

/* eslint-disable import/no-commonjs, import/no-nodejs-modules */

const { execSync } = require('child_process');
const fs = require('fs');
const { version, repository } = require('../package.json');
const { changelogPath, changelogPathFromVersion } = require('./utils/changelog');

const unreleasedChangelog = changelogPath('UNRELEASED.md');
const templateChangelog = changelogPath('_EXAMPLE.md');
const newChangelog = changelogPathFromVersion(version);

const changelogContents = fs.readFileSync(unreleasedChangelog, { encoding: 'utf8' });
fs.writeFileSync(newChangelog, `## [v${version}](https://github.com/${repository.username}/${repository.repository}/releases/v${version})\n\n${changelogContents}`);

fs.writeFileSync(unreleasedChangelog, fs.readFileSync(templateChangelog));

gitAdd(unreleasedChangelog);
gitAdd(newChangelog);

function gitAdd(file) {
	console.log('git add', file);
	return execSync(`git add ${file}`);
}
Example #20
0
 it('works for files', function() {
   var file = path.join(dir, 'foo');
   fs.writeFileSync(file, '');
   return io.exists(file).then(assert.ok);
 });
Example #21
0
function wrGPIO(pin, value){
/*---------- write value to corresponding GPIO -----------*/
	fs.writeFileSync('/sys/class/gpio/gpio' + pin + '/value', value);
}
Example #22
0
    it('can find file on path', () => {
      let filePath = path.join(dirs[1], 'foo.txt');
      fs.writeFileSync(filePath, 'hi');

      assert.strictEqual(io.findInPath('foo.txt'), filePath);
    });
//
// Helper to create hybrid application
//
function createHybridApp(config) {
    var outputDir = config.outputdir;
    if (!outputDir) outputDir = process.cwd();
    outputDir = path.resolve(outputDir);
    var projectDir = path.join(outputDir, config.appname);

    // Make sure the Cordova CLI client exists.
    var cordovaCliVersion = cordovaHelper.getCordovaCliVersion();
    if (cordovaCliVersion === null) {
        console.log('cordova command line tool could not be found.  Make sure you install the cordova CLI from https://www.npmjs.org/package/cordova.');
        process.exit(11);
    }

    var minimumCordovaCliVersionNum = miscUtils.getVersionNumberFromString(minimumCordovaCliVersion);
    var cordovaCliVersionNum = miscUtils.getVersionNumberFromString(cordovaCliVersion);
    if (cordovaCliVersionNum < minimumCordovaCliVersionNum) {
        console.log('Installed cordova command line tool version (' + cordovaCliVersion + ') is less than the minimum required version (' + minimumCordovaCliVersion + ').  Please update your version of Cordova.');
        process.exit(12);
    }

    console.log('Using cordova CLI version ' + cordovaCliVersion + ' to create the hybrid app.');

    shelljs.exec('cordova create "' + projectDir + '" ' + config.companyid + ' ' + config.appname);
    shelljs.pushd(projectDir);
    shelljs.exec('cordova platform add ios@' + cordovaPlatformVersion);
    shelljs.exec('cordova plugin add https://github.com/forcedotcom/SalesforceMobileSDK-CordovaPlugin#v' + version);

    // Remove the default Cordova app.
    shelljs.rm('-rf', path.join('www', '*'));

    // Copy the sample app, if a local app was selected.
    if (config.apptype === 'hybrid_local') {
        var sampleAppFolder = path.join(__dirname, '..', 'external', 'shared', 'samples', 'userlist');
        shelljs.cp('-R', path.join(sampleAppFolder, '*'), 'www');
    }

    // Add bootconfig.json
    var bootconfig = {
        "remoteAccessConsumerKey": config.appid || "3MVG9Iu66FKeHhINkB1l7xt7kR8czFcCTUhgoA8Ol2Ltf1eYHOU4SqQRSEitYFDUpqRWcoQ2.dBv_a1Dyu5xa",
        "oauthRedirectURI": config.callbackuri || "testsfdc:///mobilesdk/detect/oauth/done",
        "oauthScopes": ["web", "api"],
        "isLocal": config.apptype === 'hybrid_local',
        "startPage": config.startpage || 'index.html',
        "errorPage": "error.html",
        "shouldAuthenticate": true,
        "attemptOfflineLoad": false
    };
    // console.log("Bootconfig:" + JSON.stringify(bootconfig, null, 2));

    fs.writeFileSync(path.join('www', 'bootconfig.json'), JSON.stringify(bootconfig, null, 2));
    shelljs.exec('cordova prepare ios');
    shelljs.popd();

    // Inform the user of next steps.
    var nextStepsOutput =
        ['',
         outputColors.green + 'Your application project is ready in ' + projectDir + '.',
         '',
         outputColors.cyan + 'To build the new application, do the following:' + outputColors.reset,
         '   - cd ' + projectDir,
         '   - cordova build',
         '',
         outputColors.cyan + 'To run the application, start an emulator or plug in your device and run:' + outputColors.reset,
         '   - cordova run',
         '',
         outputColors.cyan + 'To use your new application in XCode, do the following:' + outputColors.reset,
         '   - open ' + projectDir + '/platforms/ios/' + config.appname + '.xcodeproj in XCode',
         '   - build and run',
         ''].join('\n');
    console.log(nextStepsOutput);
    console.log(outputColors.cyan + 'Before you ship, make sure to plug your OAuth Client ID,\nCallback URI, and OAuth Scopes into '
        + outputColors.magenta + 'www/bootconfig.json' + outputColors.reset);
}
Example #24
0
      return io.tmpDir().then(function(d) {
        tmpDir = d;

        fs.writeFileSync(path.join(d, 'foo'), 'Hello, world');
      });
Example #25
0
 rest.get(urlpath).on('complete', function(result) {
   fs.writeFileSync(filename, result);
   //console.log(result);
   return filename;
 });
Example #26
0
 return io.tmpDir().then(function(srcDir) {
   fs.writeFileSync(path.join(srcDir, 'foo'), 'hi');
   return io.tmpDir().then(function(dstDir) {
     return io.copyDir(srcDir, path.join(dstDir, 'sub'));
   });
 }).then(function(p) {
 response.images.forEach((image) =>
     fs.writeFileSync(`./images-online/${ image.name }`, image.contents));
Example #28
0
UserConfig.prototype.save = function (data) {
  var configFile = this.dir + 'current-modc.json'
  fs.writeFileSync(configFile, JSON.stringify(data))
  return true
}
Example #29
0
},function(done){//done!
  console.log(grail);
  fs.writeFileSync('./evos/anims.json',JSON.stringify(grail));
  console.log('done');
});
}).to.string(function(csvString) {
  csvString = "sep=,\n" + csvString;
  fs.writeFileSync(outputFileCsv, csvString);
});