示例#1
0
   run: function(args, callback) {

      var template = {
            config: path,
            output: path,
            x: [Array, String],
            variable: String,
            compact: Boolean,
            'complete-copy': Boolean,
            verbose: Boolean,
            'save-baseline': Boolean,
            'baseline-file': path,
            'embed-source': Boolean,
            'preserve-comments': Boolean
         },
         opts = nopt(template, { v: '--verbose' }, args, 0),
         overrides = {
            verbose: opts.verbose,
            instrumentation: {
               variable: opts.variable,
               compact: opts.compact,
               'embed-source': opts['embed-source'],
               'preserve-comments': opts['preserve-comments'],
               excludes: opts.x,
               'complete-copy': opts['complete-copy'],
               'save-baseline': opts['save-baseline'],
               'baseline-file': opts['baseline-file']
            }
         },
         config = configuration.loadFile(opts.config, overrides),
         iOpts = config.instrumentation,
         cmdArgs = opts.argv.remain,
         file,
         stats,
         stream,
         includes,
         instrumenter,
         needBaseline = iOpts.saveBaseline(),
         baselineFile = path.resolve(iOpts.baselineFile()),
         output = opts.output;

      verbose = config.verbose;
      if (cmdArgs.length !== 1) {
         return callback(inputError.create('Need exactly one filename/ dirname argument for the instrument command!'));
      }

      if (iOpts.completeCopy()) {
         includes = ['**/*'];
      }
      else {
         includes = ['**/*.js'];
      }

      var pathToProfile = path.resolve(__dirname, "..", "..", "profile.js");
      console.error(pathToProfile);

      instrumenter = new Instrumenter({
         //override the map with just function profiler
         map: {
            FunctionDeclaration: this.coverFunctionProfiler,
            FunctionExpression: this.coverFunctionProfiler
         },
         // override the preamble with just one line, that loads the profile, note it goes up 9 directories to find the ./profile.js
         // if in browser, the object profile should be pre-defined, if in nodejs, a file profile.js should be at the root of the project
         // profile should have these methods: profile.start(functionName,filename,arguments); profile.end(functionName,filename,arguments);
         preambleArray: ['var profile=(profile?profile:(function(){return require("'+ pathToProfile+ '");})());'],
         coverageVariable: iOpts.variable(),
         embedSource: iOpts.embedSource(),
         noCompact: !iOpts.compact(),
         preserveComments: true // always keep that, for proper ignoring.
      });

      if (needBaseline) {
         mkdirp.sync(path.dirname(baselineFile));
         instrumenter = new BaselineCollector(instrumenter);
         process.on('exit', function() {
            util.puts('Saving baseline coverage at: ' + baselineFile);
            fs.writeFileSync(baselineFile, JSON.stringify(instrumenter.getCoverage()), 'utf8');
         });
      }

      file = path.resolve(cmdArgs[0]);
      stats = fs.statSync(file);
      if (stats.isDirectory()) {
         if (!output) { return callback(inputError.create('Need an output directory [-o <dir>] when input is a directory!')); }
         if (output === file) { return callback(inputError.create('Cannot instrument into the same directory/ file as input!')); }
         mkdirp.sync(output);
         filesFor({
            root: file,
            includes: includes,
            excludes: opts.x || iOpts.excludes(false), // backwards-compat, *sigh*
            relative: true
         }, function(err, files) {
            if (err) { return callback(err); }
            processFiles(instrumenter, file, output, files);
         });
      } else {
         if (output) {
            stream = fs.createWriteStream(output);
         } else {
            stream = process.stdout;
         }
         stream.write(instrumenter.instrumentSync(fs.readFileSync(file, 'utf8'), file));
         if (stream !== process.stdout) {
            stream.end();
         }
      }
   },
示例#2
0
 mkdirp(path.dirname(fileName), () => {
   readStream.pipe(fs.createWriteStream(fileName));
 });
示例#3
0
文件: io.js 项目: 383366063/jplusui
	openWrite: function(path, options){
		IO.ensureDir(path);
		return FS.createWriteStream(path, options);
	},
示例#4
0
 req.busboy.on('file', function (fieldname, file, filename) {
   id = uuid.v4();
   filePath = path.join(__dirname, '../files/'+id );
   fstream = fs.createWriteStream(filePath + '.fasta');
   file.pipe(fstream);
 });
#!/usr/bin/env node

var fs = require('fs');

if (process.argv.length !== 4) {
  console.log("\tSyntax: node "+process.argv[1]+" source destination");
  process.exit();
}

var source  = fs.createReadStream(process.argv[2]);
var destiny = fs.createWriteStream(process.argv[3]);
destiny.on('close', function() {  process.stdout.write("copy finished\n"); });

source.pipe(destiny);
示例#6
0
// Excelファイルを生成するテスト for Node.js

// モジュールを取り込む
var fs = require('fs');
var officegen = require('officegen');
var xlsx = officegen('xlsx');

// 新規シートを作成
var sheet = xlsx.makeNewSheet();
sheet.name = "test";

// 直接データを書き換え
sheet.data[0] = ["商品名", "値段", "備考"];
sheet.data[1] = ["リンゴ", 340];
sheet.data[2] = ["ミカン", 980];
sheet.data[3] = ["バナナ", 280];

// セル名を指定して書き換え
sheet.setCell('C2', '新鮮');
sheet.setCell('C3', '甘い');

// ファイルを書き出す
var strm = fs.createWriteStream('test.xlsx');
xlsx.generate(strm);
 topic: function (db) {
     var stream = db.getAttachment('attachment-not-found', 'foo.txt');
     stream.pipe(fs.createWriteStream(path.join(__dirname, 'fixtures', 'not-found.txt')));
     
     stream.on('end', this.callback);
 },
示例#8
0
exports.makeWrite = function(output, announce, dir, files, options, callback) {
  var rs = make(announce, dir, files, options, callback);
  rs.pipe(fs.createWriteStream(output));
  return rs;
};
//*******************
// Load Resources
//*******************
var flash = require('connect-flash');
var express = require('express');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();


//*******************
// Log File Location
//*******************
var logFile = fs.createWriteStream('./myLogFile.log', {flags: 'a'}); 


//*******************
// Express Setup
//*******************
app.set('views', __dirname + '/mvc/view');
app.set('view engine', 'jade');

app.use(express.logger({stream: logFile}));
app.use(express.compress());

app.use(express.cookieParser());
app.use(flash());
app.use(express.bodyParser());
app.use(express.session({ secret: 'turttle' }));
示例#10
0
			https.get(download, (response) => response.pipe(fs.createWriteStream(local)).on('finish', next));
示例#11
0
var fs = require('fs');

var archiver = require('archiver');

var output = fs.createWriteStream(__dirname + '/example-output.zip');
var archive = archiver('zip');

archive.on('error', function(err) {
  throw err;
});

archive.pipe(output);

var file1 = __dirname + '/fixtures/file1.txt';
var file2 = __dirname + '/fixtures/file2.txt';

archive
  .append(fs.createReadStream(file1), { name: 'file1.txt' })
  .append(fs.createReadStream(file2), { name: 'file2.txt' });

archive.finalize(function(err, written) {
  if (err) {
    throw err;
  }

  console.log(written + ' total bytes written');
});
'use strict'

const getProfilePicture = require('.')
const fs = require('fs')

const dst = `${process.env.HOME}/Desktop/pic.jpg`

getProfilePicture()
.pipe(fs.createWriteStream(dst))
.on('close', function () {
  console.log(`open ${dst}`)
})
示例#13
0
 fs.mkdir(path.join(appDir, "css"), function (error) {
     if (error) throw error;
     //copy  public/css/base.css to public/app/css/base.css
     fs.createReadStream(path.join(publicSourceDir, "css", "base.css")).pipe(fs.createWriteStream(path.join(appDir, "css", "base.css")));
     //create index.css
     fs.writeFile(path.join(appDir, "css", "index.css"), "", function (argument) {
         // body...
     });
 });
示例#14
0
 fs.mkdir(path.join(appDir, "js"), function (err) {
     if (error) throw error;
     //create index.js
     fs.writeFile(path.join(appDir, "js", "index.js"), "define([],\nfunction() {\n});", function (argument) {
         // body...
     });
     //create tpls.js
     fs.writeFile(path.join(appDir, "js", "tpls.js"), "", function (argument) {
         // body...
     });
     //copy  public/js/jquery.tmpl.js to public/app/js/jquery.tmpl.js
     fs.createReadStream(path.join(publicSourceDir, "js", "jquery.tmpl.js")).pipe(fs.createWriteStream(path.join(appDir, "js", "jquery.tmpl.js")));
     //copy  public/js/require-jquery.js to public/app/js/require-jquery.js
     fs.createReadStream(path.join(publicSourceDir, "js", "require-jquery.js")).pipe(fs.createWriteStream(path.join(appDir, "js", "require-jquery.js")));
 });
示例#15
0
文件: ads1115.js 项目: chihchun/upm
// the SM-24 Geophone is connected to these pins
ads1115.getSample(upm.ADS1X15_MUX_DIFF_0_1);

// Set the gain based on expected VIN range to -/+ 2.048 V
// Can be adjusted based on application to as low as -/+ 0.256 V, see API
// documentation for details
ads1115.setGain(upm.ADS1X15.GAIN_TWO);

// Set the sample rate to 860 samples per second (max) and turn on continuous
// sampling
ads1115.setSPS(upm.ADS1115.SPS_860);
ads1115.setContinuous(true);

// Open the output file and start reading data once open
// Will overwrite file if it already exists
var stream = fs.createWriteStream(file);
stream.once('open', function() {
    ival = setInterval(function() {
        // Write data pairs of ID + Value for easy plotting
        stream.write(id + " " + ads1115.getLastSample().toFixed(7) + "\n");
        id++;
    }, 1); // Wait 1 ms between reads, (actuall call adds another ~1 ms overhead)
});

// Stop after 10 seconds and close the file
setTimeout(function() {
    clearInterval(ival);
    stream.end();
    console.log("Wrote " + id + " samples to file: " + file);
}, 10000);
示例#16
0
readerStream.on('end',function(){
   console.log(data);
});

readerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Read Program Ended");


var fs = require("fs");
var data2 = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data2,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});
示例#17
0
 var bundle = function() {
     gutil.log('Updated bundle build/matter-dev.js');
     b.bundle().pipe(fs.createWriteStream('build/matter-dev.js'));
 };
示例#18
0
#!/usr/bin/env node

const messages = require('./Messages.json');
const common = require('common-words');
const commonWords = common.map(obj => obj.word);
const fs = require('fs');
const outStream = fs.createWriteStream('./output.txt', { 'flags': 'a' });

commonWords.push('i');
commonWords.push('is');
commonWords.push('ss');
commonWords.push('');

const wordCounts = {};

messages.RECORDS.forEach((message) => {
  const tokens = message.body_xml.toLowerCase().replace(/[^0-9a-z\s]/gi, '').split(' ');

  tokens.forEach((token) => {
    if (commonWords.indexOf(token) === -1) {
      if (wordCounts[token] === undefined) {
        wordCounts[token] = 1;
      }
      else {
        wordCounts[token]++;
      }
    }
  });
});

const sortable = [];
 topic: function (db) {
     var stream = db.getAttachment('piped-attachment', 'foo.txt', this.callback);
     stream.pipe(fs.createWriteStream(path.join(__dirname, 'fixtures', 'README.md')));
 },
client.auth(options, function(e, api) {
    api.get('/apps/199692/android').pipe(fs.createWriteStream('android.apk'));
});
示例#21
0
var fs = require('fs');
var pat = require('path');
var os = require('os');
//console.log(path);
var stream = fs.createWriteStream(pat.join(os.tmpdir(),Math.random().toString()));
console.log(stream.path);
示例#22
0
  /**
   * Fetch the artifact with an etag
   * @param {string} tmpPath
   * @param {string} etag
   * @param {string} ts
   * @return {{ cached: true }|{ checksum: string, etag: string, first500Bytes: Buffer }}
   */
  async _download(tmpPath, etag, ts) {
    const url = this.getUrl();

    if (etag) {
      this._log.info('verifying cache of %s', chalk.bold(url));
    } else {
      this._log.info('downloading artifact from %s', chalk.bold(url));
    }

    const abc = new AbortController();
    const resp = await fetch(url, {
      signal: abc.signal,
      headers: {
        'If-None-Match': etag,
      },
    });

    if (resp.status === 304) {
      this._log.info('etags match, reusing cache from %s', chalk.bold(ts));

      abc.abort();
      return {
        cached: true,
      };
    }

    if (!resp.ok) {
      abc.abort();
      throw new Error(
        `Unable to download elasticsearch snapshot: ${resp.statusText}${headersToString(
          resp.headers,
          '  '
        )}`
      );
    }

    if (etag) {
      this._log.info('cache invalid, redownloading');
    }

    const hash = createHash(this.getChecksumType());
    let first500Bytes = Buffer.alloc(0);
    let contentLength = 0;

    mkdirp.sync(path.dirname(tmpPath));
    await asyncPipeline(
      resp.body,
      new Transform({
        transform(chunk, encoding, cb) {
          contentLength += Buffer.byteLength(chunk);

          if (first500Bytes.length < 500) {
            first500Bytes = Buffer.concat(
              [first500Bytes, chunk],
              first500Bytes.length + chunk.length
            ).slice(0, 500);
          }

          hash.update(chunk, encoding);
          cb(null, chunk);
        },
      }),
      fs.createWriteStream(tmpPath)
    );

    return {
      checksum: hash.digest('hex'),
      etag: resp.headers.get('etag'),
      contentLength,
      first500Bytes,
      headers: resp.headers,
    };
  }
示例#23
0
    ls : function(root, path){
        if(!fs.existsSync(path)){
            emit("deploy", "deploy path not found(" + path + ")");
            return null;
        }

        var files = fs.readdirSync(path);
        var size = files.length;
        var file = null;
        var absPath = null;

        for(var i = 0; i < size; i++){
            file = files[i];

            console.log("file: " + file);

            // if(file.substr(0, 1) == "." 
            //     || file.indexOf(".mix.") != -1 
            //     || file.indexOf(".md5") != -1
            //     || file.indexOf(".sha1") != -1
            //     || file.indexOf(".sha256") != -1
            //     || file.indexOf(".sha512") != -1
            // ){
            //     continue;
            // }

            absPath = root + file;

            console.log("absoulte: " + absPath);

            if(this.isDirectory(absPath)){
                this.ls(absPath + "/", absPath);
            }else if(this.isFile(absPath) && fs.existsSync(absPath + ".sha1")){
                var sign = fs.readFileSync(absPath + ".sha1", {encoding:"utf8"});

                // fs.writeFileSync(absPath + "." + sign, fs.readFileSync(absPath, "UTF-8"), {
                //     "encoding": "utf8"
                // });
                
                var _fd = fs.openSync(absPath, "r");
                var lastIndex = absPath.lastIndexOf(".");
                var name = absPath.substring(0, lastIndex);
                var ext = absPath.substring(lastIndex);
                var newName = name + "." + sign + ext;

                if(_fd){
                    var irs = fs.createReadStream(absPath, {
                        flags: 'r',
                        fd: _fd,
                        mode: "0644",
                        autoClose: true
                    });
                    var ows = fs.createWriteStream(newName, {
                        mode : "0644"
                    });

                    irs.pipe(ows);

                    HTAccessFile.addRule(absPath, sign);
                }
            }else{
                continue;
            }

        }
    }
 * Load command files
 *********************************************************/

var commands = exports.commands = require('./commands.js').commands;

// Install plug-in commands

fs.readdirSync('./chat-plugins').forEach(function (file) {
	if (file.substr(-3) === '.js') Object.merge(commands, require('./chat-plugins/' + file).commands);
});

/*********************************************************
 * Parser
 *********************************************************/

var modlog = exports.modlog = {lobby: fs.createWriteStream('logs/modlog/modlog_lobby.txt', {flags:'a+'}), battle: fs.createWriteStream('logs/modlog/modlog_battle.txt', {flags:'a+'})};

/**
 * Can this user talk?
 * Shows an error message if not.
 */
function canTalk(user, room, connection, message) {
	if (!user.named) {
		connection.popup("You must choose a name before you can talk.");
		return false;
	}
	if (room && user.locked) {
		connection.sendTo(room, "You are locked from talking in chat.");
		return false;
	}
	if (room && user.mutedRooms[room.id]) {
示例#25
0
文件: app.js 项目: wk1017553772/blog
var app = express();

//git test
// all environments
//设置端口
app.set('port', process.env.PORT || 3000);
//设置 views 文件夹为视图文件的目录,存放模板文件,__dirname 为全局变量,存储着当前正在执行脚本所在的目录名。
app.set('views', __dirname + '/views');
//设置视图模版引擎为 ejs
app.set('view engine', 'ejs');
app.use(flash());
//connect 内建的中间件,使用默认的 favicon 图标,如果想使用自己的图标,需改为 app.use(express.favicon(__dirname + '/public/images/favicon.ico')); 这里我们把自定义的 favicon.ico 放到了 public/images 文件夹下。
app.use(express.favicon());
//connect 内建的中间件,在开发环境下使用,在终端显示简单的不同颜色的日志
var accessLog = fs.createWriteStream('access.log', {flags: 'a'});
var errorLog = fs.createWriteStream('error.log', {flags: 'a'});
app.use(express.logger('dev'));
app.use(express.logger({stream: accessLog}));
//connect 内建的中间件,用来解析请求体,支持 application/json, application/x-www-form-urlencoded, 和 multipart/form-data。
app.use(express.bodyParser());
//connect 内建的中间件,可以协助处理 POST 请求,伪装 PUT、DELETE 和其他 HTTP 方法。
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
  secret: settings.cookieSecret,
  key: settings.db,
  cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
  store: new MongoStore({
    db: settings.db
  })
示例#26
0
var express = require('express'),
    path = require('path'),
    morgan = require('morgan'),
    consolidate = require('consolidate'),
    fs = require('fs'),
    swig = require('swig'),
    error_handler = require('errorhandler');

var app = express();
var router = express.Router();

var access_log_stream = fs.createWriteStream(__dirname + '/access.log',{flags: 'a'});

app.engine('html', consolidate.swig);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

app.set('port', process.env.PORT || 3000);
app.use(morgan('combined', {stream: access_log_stream}));

app.use(express.static('public'));

var users = {
        'alrock': {
            'email': '*****@*****.**',
            'website': 'http://alrock.co',
            'blog': 'http://alrockblog.com'
        }
};

var findUserByUsername = function(username, callback){
示例#27
0
//var writeStream = fs.createWriteStream('cha5/5-1-JSON.js1');
//// 当有数据的时候写入数据
//readStream.on('data', (data) => {
//    writeStream.write(data);
//});
//
//readStream.on('error', () => {
//    console.log('读写文件出错');
//});
//
//// 当没有数据流入的时候关闭流
//readStream.on('end', ()=> {
//    writeStream.end();
//});

// 上面的程序有个问题,如果写入的速度跟不上读取的速度就会造成数据丢失

var readStream = fs.createReadStream('cha5/5-1-JSON.js');
var writeStream = fs.createWriteStream('cha5/5-1-JSON.js1');
readStream.on('data',(data) =>{ //当有数据流入的时候,写入数据
    if(writeStream.write(data) === false){ // 如果没有写完,暂停读取数据
        readStream.pause();
    }
});
writeStream.on('drain', () => { // 写完后继续读取
    readStream.resume();
});
readStream.on('end', ()=>{ //当没有数据流的时候关闭数据
    writeStream.end();
})
示例#28
0
/*
 * PoisonTap
 *  by samy kamkar
 *  http://samy.pl/poisontap
 *  01/08/2016
 * 
 */

var http = require("http");
var fs = require('fs');
var util = require('util');
var backdoorPreJs = fs.readFileSync(__dirname + '/target_backdoor.js'); // this gets prepended before legit js, eg jquery.js
var backdoorHtml = fs.readFileSync(__dirname + '/backdoor.html');
var log_file = fs.createWriteStream(__dirname + '/poisontap.cookies.log', {flags : 'a'});
var log_stdout = process.stdout;
var replacejs = fs.readdirSync(__dirname + '/js');
var blinked = false;
var repobj = {};
for (var i in replacejs)
	repobj[replacejs[i].replace(/__/g, '/')] = fs.readFileSync(__dirname + '/js/' + replacejs[i]);

console.log = function(d) {
  log_file.write(util.format(d) + '\n');
  log_stdout.write(util.format(d) + '\n');
};

var startBlinking = function() {
	// Configuration
	var BLINK_MAX = 20;
	var BLINK_SPEED = 100;
示例#29
0
文件: main.js 项目: naturalethic/fez
 return new Promise(function(resolve, reject) {
   out.pipe(fs.createWriteStream(output));
   out.on("end", function() {
     resolve();
   });
 });
示例#30
0
'use strict'

var bench = require('fastbench')
var pino = require('../')
var bunyan = require('bunyan')
var bole = require('bole')('bench')
var winston = require('winston')
var fs = require('fs')
var dest = fs.createWriteStream('/dev/null')
var loglevel = require('./loglevelMock')(dest)
var plog = pino(dest)
delete require.cache[require.resolve('../')]
var plogExtreme = require('../')({extreme: true}, dest)
delete require.cache[require.resolve('../')]
var plogUnsafe = require('../')({safe: false}, dest)
delete require.cache[require.resolve('../')]
var plogUnsafeExtreme = require('../')({extreme: true, safe: false}, dest)

process.env.DEBUG = 'dlog'
var debug = require('debug')
var dlog = debug('dlog')
dlog.log = function (s) { dest.write(s) }

var deep = require('../package.json')
deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))
deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))
deep.deep.deep.deep = Object.assign({}, JSON.parse(JSON.stringify(deep)))

var max = 10
var blog = bunyan.createLogger({
  name: 'myapp',