Example #1
0
var app = express();

app.use('/',require('./readCartItems.js'));
app.use('/',require('./addCartItem.js'));
app.use('/',require('./deleteCartItem.js'));
app.use('/',require('./cartItemDetails.js'));
app.use('/',require('./newCartItem.js'));


fs.open('fixtures.json','w+',function (err) {
  if(err){
    throw err;
    return;
  }
  fs.readFile('./fixtures.json','utf8',function (data,err) {
    if(data === null){
      fs.writeFile('./fixtures.json','[]',function (err) {
        if(err) throw err;
      })
    }
    if(err) throw err;
  })
});

var server = app.listen(4000, function () {

  var host = server.address().address;
  var port = server.address().port;
  console.log("express server port is %s",port)

});
Example #2
0
var fs = require('fs');
fs.open('info.txt', 'r',
function(err, handle){
if(err){
console.log("ERROR: " + err.code
	+ " ( " + err.message + ") This file doesn't exist or is corrupted.");
	return;
}
var buf = new Buffer(100000);
	
fs.read( handle, buf, 0, 100000, null,
function(err, length){
if(err){
console.log("ERROR: " + err.code
	+ " ( " + err.message + ") This file doesn't exist or is corrupted.");
	return;
}
	console.log(buf.toString('utf8', 0, length));
	fs.close(handle, function() { /* nothing happens in here */ });
	}
);
}
);
Example #3
0
      fs.stat(file, track(function (err, stats) {
        if (err) {
          errors++;
          that.error("No such file (" + that.file + ")");
          return;
        }
        fs.open(file, 'r', track(function (err, fd) {
          if (err) {
            errors++;
            that.error("Unable to open file (" + that.file + ")");
            return;
          }

          var position = 0;
          (function read() {
            var buffer = new Buffer(chunkSize);
            fs.read(fd, buffer, 0, chunkSize, position, track(function (err, bytesRead) {
              if (err) {
                errors++;
                that.error("Error reading file (" + that.file + ")");
                return;
              }

              var slice = buffer.slice(0, bytesRead);

              // Determine headers from first slice.
              if (position == 0) {
                var headers = new meta.headers(),
                    keys = file.split('/');
                headers.set({
                  'Content-Type': meta.sniff(file, slice),
                  'Content-Length': stats.size,
                  'Content-Disposition': [ 'attachment', { 'filename': keys.pop() } ],
                });

                // Get handler and begin processing.
                that.handler = that.begin(headers);
                that.buffered = that.handler.begin && that.handler.begin(headers);
              }

              // If buffered, read file and return.
              if (that.buffered) {
                that.buffer = new Buffer(stats.size);

                fs.read(fd, that.buffer, 0, stats.size, 0, track(function (err, bytesRead) {
                  var slice = buffer.slice(0, bytesRead);
                  that.data(slice);
                }));
                return;
              }

              // Process slice.
              that.data(slice);
              position += bytesRead;

              if (position < stats.size) {
                read();
              }
            })); // fs.read
          })(); // read
        })); // fs.open
      })); // fs.stat
					fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){		// read course.json file
						if(err){
							console.log(err);
						}
						else if(bytes > 0){
							var content = buf.slice(0, bytes).toString();    		// read all file and becoming string
							var obj = JSON.parse(content);							// convert to javascript (object)

							fs.open(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml", "w", function(err,fd){
								if(err) throw err;

								var count = 0;
								var count1 = 0;
								var count2 = 0;
								var count3 = 0;
								var urlnamearr = [];

								var buf1 = new Buffer("<manifest>\n" + "\t<containers>\n");

								fs.write(fd, buf1, 0, buf1.length, 0, function(err, written, buffer){
									if(err) throw err;
    								console.log(err, written, buffer);
								})


								if(obj.units[k].type == "U"){							// for units
									count += 1;
									var myunit = [];
									myunit[count] = obj.units[k].title;
									console.log(myunit);

									for(var i = 0; i < obj.lessons.length; i++){
										if((obj.lessons[i].auto_index == true)&&
											(obj.units[k].unit_id == obj.lessons[i].unit_id)){
											count3 += 1;
										}
									}

									urlnamearr[1] = 1;

									// create cn file 
									fs.mkdir(units_elo_path + "/" + myunitfile + "/cn" + pad(count,4), function(err){
										if(err) throw err;
									})


									fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml", 
									"\t\t<container id=\"cn" + pad(count,4) + "\" type=\"cn\" display_name=\"" + myunit[count] +
									"\" url_name=\"tn" + pad(urlnamearr[count],4) + "\"/>\n", function(err){
										
										if(err) throw err;
  										console.log('Units was appended to file!');
									})

									urlnamearr[count+1] = count3 + 1;
								}

								fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
								"\t</containers>\n\n\t<contents>\n", function(err){
									if(err) throw err;
								})


								if(obj.units[k].type == "U"){
									count1 += 1;
									for(var i = 0; i < obj.lessons.length; i++){			// for lessons & fewer than its length
										if((obj.lessons[i].auto_index == true)&&
											(obj.units[k].unit_id == obj.lessons[i].unit_id)){
										
											count2 += 1;
											var mynotes = obj.lessons[i].notes.split("/");
											mynotes[2] = mynotes[2].replace(/ /g, "_");		// change path to correct
											mynotes[2] = mynotes[2].replace(/.html/, "");
											console.log(mynotes[2]);

											fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
											"\t\t<content id=\"tn" + pad(count2,4) + "\" tid=\"cn" + pad(count1,4) + 
											"\" type=\"tn\" url_name=\"" + mynotes[2] + "\"/>\n", function(err){

												if(err) throw err;
											})
										}
									}
								}

								fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
								"\t</contents>\n</manifest>",function(err){
									if(err) throw err;
								})

								fs.close(fd, function(){							// close aggregation.xml file
      								console.log('Done');
    							})
							})

						}
					})
		function open_a(next) {
			fs.open(__dirname + '/a.txt', 'r', next);
		},
Example #6
0
 function(stat, callback) {
   fs.open(src, 'r', function(err, fd) { callback(err, stat, fd); });
 },
Example #7
0
        }

        try {
          fs.move(output + '_tmp.pdf', output);
        } catch (e) {
          error(e);
        }
        quit('Rendered to: ' + output, new Date().getTime());
      }, render_time);
    }
  });
}

if (cookie_file) {
  try {
    f = fs.open(cookie_file, "r");
    cookies = JSON.parse(f.read());
    fs.remove(cookie_file);
  } catch (e) {
    console.log(e);
  }
  phantom.cookiesEnabled = true;
  phantom.cookies = cookies;
}

if (system.args.length < 3 || system.args.length > 13) {
  print_usage() && phantom.exit(2);
} else {
  address = system.args[1];
  output  = system.args[2];
Example #8
0
var ZIP = require("./zip");
var FS = require("fs");

console.log("-------------------");
console.log("READ from Buffer");

var data = FS.readFileSync("zip.zip")
var reader = ZIP.Reader(data);
console.log(reader.toObject('utf-8'));

console.log("-------------------");
console.log("READ from file descriptor");

FS.open("zip.zip", "r", "0666", function(err, fd) {
  var reader = ZIP.Reader(fd);
	console.log(reader.toObject('utf-8'));
});

Example #9
0
var page = require('webpage').create(),
    i;
var fs = require('fs');

var outout = fs.open('domains2.txt', 'a');

function crawl(i) {
    var url = 'http://www.dl.ro/index/search/pageno/' + i;
    console.log(url);
    if (i > 3453) {
        phantom.exit();
    }
    page.open(url, function (status) {
        console.log(status);
        if (status == 'fail') {
            setTimeout(crawl.bind(this, i), 300000);
            console.log("Sleeping for 5 minutes.");
            return;
        }
        //BROWSER
        var results = page.evaluate(function () {
            var list = document.querySelectorAll('html body table tbody tr td table tbody tr td table tbody tr td table tbody tr td a'),
                pizza = [],
                i;
            for (i = 0; i < list.length; i++) {
                if (i % 3 == 2)
                    pizza.push(list[i].innerText);
            }
            return pizza;
        });
        //OUT OF BROWSER
Example #10
0
/**
 * Created on 2016/7/10.
 */
var fs = require('fs');
var buf = new Buffer(1024);

fs.open('input.txt', 'r+', function (err, fd) {
    if (err) {
        return console.error(err);
    }
    console.log('open success...');
    console.log('start reading...');
    fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {
        if (err) {
            return console.error(err);
        }
        console.log(bytes + 'bytes read');
        if (bytes > 0) {
            console.log(buf.slice(0, bytes).toString());
        }
        fs.close(fd, function (err) {
            if (err) {
                return console.error(err);
            }
            console.log('close success');
        })
    })
});
Example #11
0
fs.open(path.join(__dirname, 'config.json'), 'r', function(err) {
	if (!err) {
		if (nconf.get('daemon') !== 'false' && nconf.get('daemon') !== false) {
			if (file.existsSync(pidFilePath)) {
				try {
					var	pid = fs.readFileSync(pidFilePath, { encoding: 'utf-8' });
					process.kill(pid, 0);
					process.exit();
				} catch (e) {
					fs.unlinkSync(pidFilePath);
				}
			}

			require('daemon')({
				stdout: process.stdout,
				stderr: process.stderr
			});

			fs.writeFile(__dirname + '/pidfile', process.pid);
		}

		async.series([
			Loader.init,
			Loader.displayStartupMessages,
			Loader.start
		], function(err) {
			if (err) {
				console.log('[loader] Error during startup: ' + err.message);
			}
		});
	} else {
		// No config detected, kickstart web installer
		var child = require('child_process').fork('app');
	}
});
Example #12
0
exports.init = function(){
    var defaultDir = settings.getWorkingDirectory();
    //check if file exists
    if(!fs.existsSync(defaultDir)){

      fs.mkdirSync(defaultDir, function(err){
        if(err){
          console.log('Error creating default directory');
        }
      });
    }

    if(!fs.existsSync(defaultDir+'/saves')){
      fs.mkdirSync(defaultDir+'/saves');
    }

    fs.open(defaultDir+'/districts.json', 'r+', function(err){
      var districts;
      if(err){
          console.log('Cannot find districts file...');
          districts = {
            name: 'Districts',
            data: createDistricts()
          };
          fs.writeFile(defaultDir+'/districts.json', JSON.stringify(districts, null, '\t'), function(err){
            if(err){
              console.log('Unable to write districts.json');
            }
          });
      }else{
        //load data
        districts = loader.DistrictsFromFile(defaultDir+'/districts.json');
        console.log('Loaded districts: ' + districts.length);
      }
    });

    fs.open(defaultDir+'/population.json', 'r+', function(err){
      var population;
      if(err){
          console.log('Cannot find population file...');
          population = {
            name: 'Population',
            data: createPopulation()
          };
          fs.writeFile(defaultDir+'/population.json', JSON.stringify(population, null, '\t'), function(err){
            if(err){
              console.log('Unable to write population.json');
            }
          });
      }else{
        //load data
        population = loader.DistrictsFromFile(defaultDir+'/population.json');
        console.log('Loaded population: ' + population.length);
      }
    });

    fs.open(defaultDir+'/actions.json', 'r+', function(err){
      var actions;

      if(err){
        console.log('Cannot find actions file...');
        actions = {
          name: 'Actions',
          data: createActions()
        };
        fs.writeFile(defaultDir+'/actions.json', JSON.stringify(actions, null, '\t'), function(err){
          if(err){
            console.log('Unable to write actions.json');
          }
        });
      }else{
        //load data
        actions = loader.ActionsFromFile(defaultDir+'/actions.json');
        console.log('Loaded actions: ' + actions.length);
      }
    });
};
fs.open('nkf32_sjis.txt', 'w', function (err, fd) {

  var nkf1 = spawn('nkf32.exe', ['-W', '-s', 'nkf32_utf8.txt']);
  nkf1.stdin.end();

  nkf1.stdout.on('readable', function () {
    var buff = nkf1.stdout.read();
    console.log(buff);
    if (buff === null) return;
    fs.write(fd, buff, 0, buff.length, null, function () {
      console.log('write callback');
    });
  });

  nkf1.stdout.on('end', function () {
    console.log('end: ', arguments.length, arguments);
    fs.close(fd, function (err) {
      if (err) throw err;
      console.log('end close: ', arguments.length, arguments);
    });
  });

  nkf1.on('error', function (err) {
    console.log('error: ', err);
  });

  nkf1.on('exit', function (code) {
    console.log('exit: ', code);
  });

}); // fs.open
Example #14
0
var addFile	= function (options, callback) {
	fs.open(options.path, 'a' , callback);	
};
Example #15
0
 function (cb) {
   fs.open(path, 'r', cb);
 },
Example #16
0
function Joystick(id, deadzone, sensitivity) {

  var self = this;

  this.id = id;

  var buffer = new Buffer(8);
  var fd;

  // Last reading from this axis, used for debouncing events using sensitivty setting
  var lastAxisValue = [];
  var lastAxisEmittedValue = [];

  events.EventEmitter.call(this);

  function parse(buffer) {

      var event =  {
        time : buffer.readUInt32LE(0),
        value: buffer.readInt16LE(4),
        number: buffer[7]
      };
      
      var type = buffer[6];
      
      if (type & 0x80) {
        event.init = true;
      }

      if (type & 0x01) {
        event.type = 'button';
      }

      if (type & 0x02) {
        event.type = 'axis';
      }

      event.id = self.id;
      
      return event;
  }

  function startRead() {
    fs.read(fd, buffer, 0, 8, null, onRead);
  }

  function onOpen(err, fdOpened) {

    if (err) {
      return self.emit("error", err);
    }

    fd = fdOpened;
    startRead();
  }

  function onRead(err, bytesRead) {

    if (err) {
      return self.emit("error", err);
    }

    var event = parse(buffer);

    var squelch = false;

    if (event.type === 'axis') {

      if (sensitivity) {
        if (lastAxisValue[event.number] && Math.abs(lastAxisValue[event.number] - event.value) < sensitivity) {
          // data squelched due to sensitivity, no self.emit
          squelch = true;
        } else {
          lastAxisValue[event.number] = event.value;
        }
      }

      if (deadzone && Math.abs(event.value) < deadzone) {
        event.value = 0;
      }

      if (lastAxisEmittedValue[event.number] === event.value) {
        squelch = true;
      } else {
        lastAxisEmittedValue[event.number] = event.value;
      }
    }

    if (!squelch) {
      self.emit(event.type, event);
    }

    if (fd) {
      startRead();
    }
  }

  this.close = function (callback) {
    fs.close(fd, callback);
    fd = undefined;
  };

  fs.open("/dev/input/js" + id, "r", onOpen);
}
Example #17
0
/**
 * @author Administrator
 * fs.open(path,flags,[mode],[callback(err,fd)])
 */

var fs = require('fs');
fs.open('file.txt', 'r', '0666', function(err, fd) {
    if (err) {
        console.error(err);
    } else {
        console.log(fd);
    }
});

console.log('opening....');
Example #18
0

var fileName = process.cwd() + "/resources/greeting.txt";
var expectedContents = "Hello IoT.js!!";
var flags = "r";
var mode = 438;


// test async open & read
fs.open(fileName, flags, mode, function(err, fd) {
  if (err) {
    throw err;
  } else {
    var buffer = new Buffer(64);
    fs.read(fd, buffer, 0, buffer.length, 0, function(err, bytesRead, buffer) {
      if (err) {
        throw err;
      } else {
        assert.equal(buffer.toString(), expectedContents);
      }
    });
  }
});


// error test
assert.throws(
  function() {
    fs.openSync("non_exist_file", flags, mode);
  },
  Error
);
(function () {
	"use strict";

	var config = {
		/* define locations of mandatory javascript files */
		HIGHCHARTS: 'highstock.js',
		HIGHCHARTS_MORE: 'highcharts-more',
		JQUERY: 'jquery-1.8.2.min.js'
	},
	/* Internal */
		page = require('webpage').create(),
		fs = require('fs'),
		system = require('system'),
		args,
		HC = {},
		pick,
		mapArguments,
		scaleAndClipPage,
		input,
		constr,
		callback,
		width,
		callbackStr,
		optionsStr,
		output,
		outputExtension,
		pdfOutput,
		svg,
		svgFile,
		svgElem,
		timer;

	HC.imagesLoaded = 'Highcharts.imagesLoaded:7a7dfcb5df73aaa51e67c9f38c5b07cb';
	window.imagesLoaded = false;

	page.onConsoleMessage = function (msg) {
		console.log(msg);
		/*
		 * Ugly hack, but only way to get messages out of the 'page.evaluate()'
		 * sandbox. If any, please contribute with improvements on this!
		 */
		if (msg === HC.imagesLoaded) {
			window.imagesLoaded = true;
		}
	};

	page.onAlert = function (msg) {
		console.log(msg);
	};

	pick = function () {
		var args = arguments, i, arg, length = args.length;
		for (i = 0; i < length; i += 1) {
			arg = args[i];
			if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
				return arg;
			}
		}
	};

	mapArguments = function () {
		var map = {},
			i;
		for (i = 0; i < system.args.length; i += 1) {
			if (system.args[i].charAt(0) === '-') {
				map[system.args[i].substr(1, i.length)] = system.args[i + 1];
			}
		}
		return map;
	};

	/* scale and clip the page */
	scaleAndClipPage = function (svg, pdf) {
		/*	param: svg: The scg configuration object
				param: pdf: boolean, if true set papersize
		*/

		var zoom = 1,
			pageWidth = pick(args.width, svg.width),
			clipwidth, clipheight;

		if (parseInt(pageWidth, 10) == pageWidth) {
			zoom = pageWidth / svg.width;
		}

		/* set this line when scale factor has a higher precedence
		scale has precedence : page.zoomFactor = args.scale  ? zoom * args.scale : zoom;*/

		/* args.width has a higher precedence over scaling, to not break backover compatibility */
		page.zoomFactor = args.scale && args.width == undefined ? zoom * args.scale : zoom;

		clipwidth = svg.width * page.zoomFactor;
		clipheight = svg.height * page.zoomFactor;

		/* define the clip-rectangle */
		page.clipRect = {
			top: 0,
			left: 0,
			width: clipwidth,
			height: clipheight
		};

		/* for pdf we need a bit more paperspace in some cases for example (w:600,h:400), I don't know why.*/
		if (pdf) {
			page.paperSize = { width: clipwidth, height: clipheight + 2};
		}
	};

	/* get the arguments from the commandline and map them */
	args = mapArguments();

	if (args.length < 1) {
		console.log('Usage: highcharts-convert.js -infile URL -outfile filename -scale 2.5 -width 300 -constr Chart -callback callback.js');
		console.log('Commandline parameter width is used for scaling, not for creating the chart');
		phantom.exit(1);
	} else {
		input = args.infile;
		output = pick(args.outfile, "chart.png");
		constr = pick(args.constr, 'Chart');
		callback = args.callback;
		width = args.width;

		outputExtension = output.split('.').pop();
		pdfOutput = outputExtension === 'pdf';

		/* Decide to generate the page from javascript or to load from svg file. */

		if (input.split('.').pop() === 'json') {
			// We have a json file, -> go headless!

			// load necessary libraries
			page.injectJs(config.JQUERY);
			page.injectJs(config.HIGHCHARTS);
			page.injectJs(config.HIGHCHARTS_MORE);

			// load options from file
			if (input !== undefined) {
				optionsStr = fs.read(input);
			} else {
				console.log('No options file specified!');
				phantom.exit();
			}

			// load callback from file
			if (callback !== undefined) {
				callbackStr = fs.read(callback);
			}

			// load chart in page and return svg height and width
			svg = page.evaluate(function (width, constr, optionsStr, callbackStr, pdfOutput) {

				var imagesLoadedMsg = 'Highcharts.imagesLoaded:7a7dfcb5df73aaa51e67c9f38c5b07cb', $container, chart,
					nodes, nodeIter, elem, opacity;

				// dynamic script insertion
				function loadScript(varStr, codeStr) {
					var $script = $('<script>').attr('type', 'text/javascript');
					$script.html('var ' + varStr + ' = ' + codeStr);
					document.getElementsByTagName("head")[0].appendChild($script[0]);
				}

				// are all images loaded in time?
				function logCounter(counter) {
					counter -= 1;
					if (counter < 1) {
						console.log(imagesLoadedMsg);
					}
				}

				function loadImages() {
					// are images loaded?
					var $images = $('svg image'), counter, i, img;

					if ($images.length > 0) {

						counter = $images.length;

						for (i = 0; i < $images.length; i += 1) {
							img = new Image();
							img.onload = logCounter(counter);
							/* force loading of images by setting the src attr.*/
							img.src = $images[i].getAttribute('href');
						}
					} else {
						// no images set property to all images
						// loaded
						console.log(imagesLoadedMsg);
					}
				}

				if (optionsStr !== 'undefined') {
					loadScript('options', optionsStr);
				}

				if (callbackStr !== 'undefined') {
					loadScript('callback', callbackStr);
				}

				$(document.body).css('margin', '0px');
				$container = $('<div>').appendTo(document.body);
				$container.attr('id', 'container');

				// disable animations
				Highcharts.SVGRenderer.prototype.Element.prototype.animate = Highcharts.SVGRenderer.prototype.Element.prototype.attr;

				if (!options.chart) {
					options.chart = {};
				}

				options.chart.renderTo = $container[0];

				// check if witdh is set. Order of precedence:
				// args.width, options.chart.width and 600px

				// OLD. options.chart.width = width || options.chart.width || 600;
				// Notice we don't use commandline parameter width here. Commandline parameter width is used for scaling.
				options.chart.width = (options.exporting && options.exporting.sourceWidth) || options.chart.width || 600;
				options.chart.height = (options.exporting && options.exporting.sourceHeight) || options.chart.height || 400;



				chart = new Highcharts[constr](options, callback);

				// ensure images are all loaded
				loadImages();

				if (pdfOutput) {
					/*
					 * remove stroke-opacity paths, Qt shows
					 * them as fully opaque in the PDF
					 */
					nodes = document.querySelectorAll('*[stroke-opacity]');

					for (nodeIter = 0; nodeIter < nodes.length; nodeIter += 1) {
						elem = nodes[nodeIter];
						opacity = elem.getAttribute('stroke-opacity');
						elem.removeAttribute('stroke-opacity');
						elem.setAttribute('opacity', opacity);
					}
				}

				return {
					//html: $container[0].firstChild.innerHTML,
					html: $('div.highcharts-container')[0].innerHTML,
					width: chart.chartWidth,
					height: chart.chartHeight
				};

			}, width, constr, optionsStr, callbackStr, pdfOutput);

			try {
				// save the SVG to output or convert to other formats
				if (outputExtension === 'svg') {
					svgFile = fs.open(output, "w");
					// set in xlink namespace for images.
					svgFile.write(svg.html.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ')
						.replace(/ href=/g, ' xlink:href=').replace(/<\/svg>.*?$/, '</svg>'));
					svgFile.close();
					phantom.exit();
				} else {
					// check every 50 ms if all images are loaded
					window.setInterval(function () {
						if (!window.imagesLoaded) {
							console.log('loading images...');
						} else {
							console.log('done loading images');
							scaleAndClipPage(svg, pdfOutput);
							page.render(output);
							clearTimeout(timer);
							phantom.exit();
						}
					}, 50);
					// we have a 3 second timeframe..
					timer = window.setTimeout(function () {
						phantom.exit();
					}, 3000);
				}
			} catch (e) {
				console.log(e);
			}
		} else { /* render page directly from svg file */
			page.open(input, function (status) {
				var nodeIter, opacity, elem, svg;
				if (status !== 'success') {
					console.log('Unable to load the address!');
					phantom.exit();
				} else {
					svg = page.evaluate(function (pdfOutput) {
						if (pdfOutput) {
							/*
							 * remove stroke-opacity paths, Qt shows them as
							 * fully opaque in the PDF, replace attributes with
							 * opacity
							 */
							var nodes = document.querySelectorAll('*[stroke-opacity]');

							for (nodeIter = 0; nodeIter < nodes.length; nodeIter += 1) {
								elem = nodes[nodeIter];
								opacity = elem.getAttribute('stroke-opacity');
								elem.removeAttribute('stroke-opacity');
								elem.setAttribute('opacity', opacity);
							}
						}

						svgElem = document.getElementsByTagName('svg')[0];
						return {
							width: svgElem.getAttribute("width"),
							height: svgElem.getAttribute("height")
						};
					}, pdfOutput);

					scaleAndClipPage(svg, pdfOutput);
					page.render(output);
					phantom.exit();
				}
			});
		}
	}
}());
Example #20
0
var fs = require('fs');

fs.open('content.txt', 'r', function(err, fd) {
	if (err) {
		console.error(err);
		return;
	}

	var buf = new Buffer(8);
	fs.read(fd, buf, 0, 8, null, function(err, bytesRead, buffer) {
		if (err) {
			console.error(err);
			return;
		}

		console.log('bytesRead: ' + bytesRead);
		console.log(buffer);
	})
});
/* author: Jeremy																				       */
/* 1.function Units_open_aggregation_file() will create elo_aggreagation file.						   */
/* 2.function Units_mkdirectory() uses createfile() to create elo_aggregation.xml, elo_manifest.xml    */
/*   and elo_metadata.xml under directory. 															   */
/* 3.function units_open_manifest_file will create elo_manifest.xml. 								   */
/* 4.function pad will generate a four-digit number ex: 0001.										   */



/* function Units_open_aggregation_file() will create elo_aggreagation file. */
function Units_open_aggregation_file(myunitfile, k){

	var x = document.getElementById("fileImportDialog");
	var message = "";
	var fs = require("fs");
	var buf = new Buffer(1000000);								// buffer like an array (1MB)

	if ("files" in x) {
		if(x.files.length == 0){
			message = "Select a GCB file.";
		}
		else{
				var file = x.files[0];								// x.files[0] for the first file
				var units_elo_path = file.path.replace(file.name, "") + "Units_ELO_" + file.name.replace(/ /g, "_");
				if("name" in file){
					message += "You selected a file : " + file.name + "<br>";
				}
				console.log("Going to read GCB directory");
				coursejsonpath = file.path + "/files/data/course.json";		// To find where is course.json file
				
				fs.open(coursejsonpath, "r", function(err, fd){
					if(err){
						return console.error(err);
					}
					console.log("course.json opened successfully!");
					console.log("Going to read the course.json file");
					fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){		// read course.json file
						if(err){
							console.log(err);
						}
						else if(bytes > 0){
							var content = buf.slice(0, bytes).toString();    		// read all file and becoming string
							var obj = JSON.parse(content);							// convert to javascript (object)

							fs.open(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml", "w", function(err,fd){
								if(err) throw err;

								var count = 0;
								var count1 = 0;
								var count2 = 0;
								var count3 = 0;
								var urlnamearr = [];

								var buf1 = new Buffer("<manifest>\n" + "\t<containers>\n");

								fs.write(fd, buf1, 0, buf1.length, 0, function(err, written, buffer){
									if(err) throw err;
    								console.log(err, written, buffer);
								})


								if(obj.units[k].type == "U"){							// for units
									count += 1;
									var myunit = [];
									myunit[count] = obj.units[k].title;
									console.log(myunit);

									for(var i = 0; i < obj.lessons.length; i++){
										if((obj.lessons[i].auto_index == true)&&
											(obj.units[k].unit_id == obj.lessons[i].unit_id)){
											count3 += 1;
										}
									}

									urlnamearr[1] = 1;

									// create cn file 
									fs.mkdir(units_elo_path + "/" + myunitfile + "/cn" + pad(count,4), function(err){
										if(err) throw err;
									})


									fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml", 
									"\t\t<container id=\"cn" + pad(count,4) + "\" type=\"cn\" display_name=\"" + myunit[count] +
									"\" url_name=\"tn" + pad(urlnamearr[count],4) + "\"/>\n", function(err){
										
										if(err) throw err;
  										console.log('Units was appended to file!');
									})

									urlnamearr[count+1] = count3 + 1;
								}

								fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
								"\t</containers>\n\n\t<contents>\n", function(err){
									if(err) throw err;
								})


								if(obj.units[k].type == "U"){
									count1 += 1;
									for(var i = 0; i < obj.lessons.length; i++){			// for lessons & fewer than its length
										if((obj.lessons[i].auto_index == true)&&
											(obj.units[k].unit_id == obj.lessons[i].unit_id)){
										
											count2 += 1;
											var mynotes = obj.lessons[i].notes.split("/");
											mynotes[2] = mynotes[2].replace(/ /g, "_");		// change path to correct
											mynotes[2] = mynotes[2].replace(/.html/, "");
											console.log(mynotes[2]);

											fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
											"\t\t<content id=\"tn" + pad(count2,4) + "\" tid=\"cn" + pad(count1,4) + 
											"\" type=\"tn\" url_name=\"" + mynotes[2] + "\"/>\n", function(err){

												if(err) throw err;
											})
										}
									}
								}

								fs.appendFile(units_elo_path + "/" + myunitfile + "/elo_aggregation.xml",
								"\t</contents>\n</manifest>",function(err){
									if(err) throw err;
								})

								fs.close(fd, function(){							// close aggregation.xml file
      								console.log('Done');
    							})
							})

						}
					})

					fs.close(fd, function(err){										// close course.json file
						if(err){
							console.log(err);
						}
						console.log("GCB File closed successfully !");
					})
				})
		}
	}
	else{
		if(x.value = ""){
			message += "Select a GCB file";
		}
		else{
			message += "The files property is not supported by your browerser!";
		}
	}

	document.getElementById("demo").innerHTML = message;
};
Example #22
0
/*
* 两个两个读取
* */
var fs = require("fs");
var list = [];
fs.open("index.txt","r",function(err,fd){
    var pos = 0;
    function read(){
        var buffer = new Buffer(3);
        fs.read(fd,buffer,0,3,pos,function(err,bytesRead){
            list.push(buffer.slice(0,bytesRead));
            console.log(buffer,bytesRead);
            pos += bytesRead;
            if(bytesRead > 0){
                read();
            }else{
                var result = Buffer.concat(list);
                console.log(result.toString());
            }
        });
    }
    read();

});
Example #23
0
var fs = require('fs');
function readFruit(fd, fruits){
	var buf = new Buffer(5);
	buf.fill();
	fs.read(fd, buf, 0, 5, null, function(err, bytes, data){
		if( bytes > 0){
			console.log("read %dbytes", bytes);
			fruits += data;
			readFruit(fd, fruits);
		}else{
			fs.close(fd);
			console.log("Fruits: %s", fruits);
		}
	});
}
fs.open('fruit.txt','r',function (err, fd) {
	readFruit(fd, "");
});
Example #24
0
var fs = require("fs");
var buf = new Buffer(1024);

console.log("准备打开已存在的文件!");
fs.open('input.txt', 'r+', function(err, fd){
	if (err) {
		return console.error(err);
	}
	console.log("文件打开成功!");
	console.log("准备读取文件:");
	fs.read(fd, buf, 0, buf.length, 0,function(err, bytes){
		if(err){
			console.log(err);
		}
		console.log(bytes + " 字节被读取");

		//仅输出读取的字节
		if(bytes > 0){
			console.log(buf.slice(0, bytes).toString());
		}
	});
});
Example #25
0
		function open_b(next) {
			fs.open(__dirname + '/b.txt', 'a', next);
		},
Example #26
0
var fs = require('fs');
var fruitBowl = ['apple', 'orange', 'banana', 'grapes'];

function writeFruit(fd) {
	if (fruitBowl.length) {
		var fruit = fruitBowl.pop() + " ";
		fs.write(fd, fruit, null, null, function(err, bytes) {
			if (err) {
				console.log("File Write Failed.")
			} else {
				console.log("Wrote: %s %dbytes", fruit, bytes);
				writeFruit(fd);
			}
		});
	} else {
		fs.close(fd);
	}
}

fs.open('./fruit.txt', 'w', function(err, fd) {
	writeFruit(fd);
});
Example #27
0
var fs = require('fs');

fs.open('/home/cicas/Documents/spec.txt', 'a', (err, fd) => {
  // body...
  if (err)
  {
    throw err;
  }

  var writeBuffer = new Buffer('writing string in file');
  var bufferOffset = 0;
  var bufferLength = writeBuffer.length;
  var filePosition = null;

  fs.write(fd, writeBuffer, bufferOffset, bufferLength, filePosition,
    function (err, written)
    {
      if (err)
      {
        throw err;
      }

      console.log('wrote ' + written + ' bytes');
    });
});
Example #28
0
function setupHistory(repl, historyPath, oldHistoryPath, ready) {
  if (!historyPath) {
    try {
      historyPath = path.join(os.homedir(), '.node_repl_history');
    } catch (err) {
      repl._writeToOutput('\nError: Could not get the home directory.\n' +
                          'REPL session history will not be persisted.\n');
      repl._refreshLine();

      debug(err.stack);
      repl._historyPrev = _replHistoryMessage;
      return ready(null, repl);
    }
  }

  var timer = null;
  var writing = false;
  var pending = false;
  repl.pause();
  fs.open(historyPath, 'a+', oninit);

  function oninit(err, hnd) {
    if (err) {
      // Cannot open history file.
      // Don't crash, just don't persist history.
      repl._writeToOutput('\nError: Could not open history file.\n' +
                          'REPL session history will not be persisted.\n');
      repl._refreshLine();
      debug(err.stack);

      repl._historyPrev = _replHistoryMessage;
      repl.resume();
      return ready(null, repl);
    }
    fs.close(hnd, onclose);
  }

  function onclose(err) {
    if (err) {
      return ready(err);
    }
    fs.readFile(historyPath, 'utf8', onread);
  }

  function onread(err, data) {
    if (err) {
      return ready(err);
    }

    if (data) {
      repl.history = data.split(/[\n\r]+/, repl.historySize);
    } else if (oldHistoryPath === historyPath) {
      // If pre-v3.0, the user had set NODE_REPL_HISTORY_FILE to
      // ~/.node_repl_history, warn the user about it and proceed.
      repl._writeToOutput(
          '\nThe old repl history file has the same name and location as ' +
          `the new one i.e., ${historyPath} and is empty.\nUsing it as is.\n`);
      repl._refreshLine();

    }  else if (oldHistoryPath) {
      // Grab data from the older pre-v3.0 JSON NODE_REPL_HISTORY_FILE format.
      repl._writeToOutput(
          '\nConverting old JSON repl history to line-separated history.\n' +
          `The new repl history file can be found at ${historyPath}.\n`);
      repl._refreshLine();

      try {
        // Pre-v3.0, repl history was stored as JSON.
        // Try and convert it to line separated history.
        const oldReplJSONHistory = fs.readFileSync(oldHistoryPath, 'utf8');

        // Only attempt to use the history if there was any.
        if (oldReplJSONHistory) repl.history = JSON.parse(oldReplJSONHistory);

        if (!Array.isArray(repl.history)) {
          throw new Error('Expected array, got ' + typeof repl.history);
        }
        repl.history = repl.history.slice(0, repl.historySize);
      } catch (err) {
        if (err.code !== 'ENOENT') {
          return ready(
            new Error(`Could not parse history data in ${oldHistoryPath}.`));
        }
      }
    }

    fs.open(historyPath, 'w', onhandle);
  }

  function onhandle(err, hnd) {
    if (err) {
      return ready(err);
    }
    repl._historyHandle = hnd;
    repl.on('line', online);

    // reading the file data out erases it
    repl.once('flushHistory', function() {
      repl.resume();
      ready(null, repl);
    });
    flushHistory();
  }

  // ------ history listeners ------
  function online() {
    repl._flushing = true;

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(flushHistory, kDebounceHistoryMS);
  }

  function flushHistory() {
    timer = null;
    if (writing) {
      pending = true;
      return;
    }
    writing = true;
    const historyData = repl.history.join(os.EOL);
    fs.write(repl._historyHandle, historyData, 0, 'utf8', onwritten);
  }

  function onwritten(err, data) {
    writing = false;
    if (pending) {
      pending = false;
      online();
    } else {
      repl._flushing = Boolean(timer);
      if (!repl._flushing) {
        repl.emit('flushHistory');
      }
    }
  }
}
			function (cb) {
				fs.open(self._zipFile.filePath, 'r', cb);
			},
'use strict';
try {
  var args = require('system').args;

  var input_path = args[1];
  var output_path = args[2];

  var fs = require('fs');
  var input_file = fs.open(input_path, 'r');
  var output_file = fs.open(output_path, 'w');

  var argument = JSON.parse(input_file.read());
  var page = require('webpage').create();
  var response_dict = {};

  input_file.close();

  if (argument['cookies']) {
    for (key in argument['cookies']) {
      phantom.addCookie({
        name: key,
        value: argument['cookies'][key],
        domain: argument['domain'],
      })
    }
  }

  page.settings = {
    userAgent: argument['headers']['User-Agent'],
    ignoreSslErrors: true,
    javascriptEnabled: true,