Example #1
0
fnAtLeast2Called3();

const failFixtures = [
  [
    join(common.fixturesDir, 'failmustcall1.js'),
    'Mismatched <anonymous> function calls. Expected exactly 2, actual 1.'
  ], [
    join(common.fixturesDir, 'failmustcall2.js'),
    'Mismatched <anonymous> function calls. Expected at least 2, actual 1.'
  ]
];
for (const p of failFixtures) {
  const [file, expected] = p;
  execFile(process.argv[0], [file], common.mustCall((ex, stdout, stderr) => {
    assert.ok(ex);
    assert.strictEqual(stderr, '');
    const firstLine = stdout.split('\n').shift();
    assert.strictEqual(firstLine, expected);
  }));
}

// hijackStderr and hijackStdout
const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ];
[ 'err', 'out' ].forEach((txt) => {
  const stream = process[`std${txt}`];
  const originalWrite = stream.write;

  common[`hijackStd${txt}`](common.mustCall(function(data) {
    assert.strictEqual(data, HIJACK_TEST_ARRAY[stream.writeTimes]);
  }, HIJACK_TEST_ARRAY.length));
  assert.notStrictEqual(originalWrite, stream.write);
 t.test('raw TAP > TAP consumer > TAP producer', function(t) {
   var args = [bin, '--tap', useConsole]
   execFile(node, args, assertTapDirectives.bind(this, t))
 })
 t.test('TAP producer via require("tap")', function(t) {
   var args = [useTap]
   execFile(node, args, assertTapDirectives.bind(this, t))
 })
Example #4
0
//console.log(process.version, process.arch, process.config.variables.target_arch);

if (process.config.variables.target_arch !== 'ia32') {
    // needed for x86_64
    confArgs.push('CFLAGS=-fPIC');
    confArgs.push('CXXFLAGS=-fPIC');
} else {
    // needed for multilib builds on x86_64 host
    confArgs.push('CFLAGS=-m32');
    confArgs.push('CXXFLAGS=-m32');
}

console.log(path.join(libzim, 'autogen.sh'));
child_process.execFile(path.join(libzim, 'autogen.sh'), [
    //'autogen.sh'
], {
    cwd: libzim,
    stdio: 'inherit'
}, function(err, stdout, stderr) {
    if (err) { throw err; }

    console.log(confArgs.join(' '));
    child_process.execFile(confArgs[0], confArgs.slice(1), {
        cwd: confdir,
        stdio: 'inherit'
    }, function(err, stdout, stderr) {
        if (err) { throw err; }
        process.exit(0);
    });
});
Example #5
0
 beforeEach((done) => {
   cp.execFile(`${__dirname}/../scripts/populate.sh`, { cwd: `${__dirname}/../scripts` }, () => {
     done();
   });
 });
assert.throws(function() { spawn(cmd, a, s); }, invalidArgTypeError);


// Verify that execFile has same argument parsing behavior as spawn.
//
// function execFile(file=f [,args=a] [, options=o] [, callback=c]) has valid
// combinations:
//   (f)
//   (f, a)
//   (f, a, o)
//   (f, a, o, c)
//   (f, a, c)
//   (f, o)
//   (f, o, c)
//   (f, c)
execFile(cmd);
execFile(cmd, a);
execFile(cmd, a, o);
execFile(cmd, a, o, c);
execFile(cmd, a, c);
execFile(cmd, o);
execFile(cmd, o, c);
execFile(cmd, c);

// Variants of undefined as explicit 'no argument' at a position.
execFile(cmd, u, o, c);
execFile(cmd, a, u, c);
execFile(cmd, a, o, u);
execFile(cmd, n, o, c);
execFile(cmd, a, n, c);
execFile(cmd, a, o, n);
Example #7
0
File: git.js Project: bmeck/npm
function execGit(args, options, cb) {
  return exec(git, prefixGitArgs().concat(args || []), options, cb)
}
Example #8
0
var exec = require('child_process').execFile;

var args = ['kitten.jpg', 'lol.png']

exec('convert', args, function(err, stdout, stderr) {

    console.log(stdout)

})
Example #9
0
function queueTrack(file, cb) {
	child_process.execFile('./mpd-queue.sh', [mpdPassword, file], function (err, stdout, stderr) {
		console.log("Queued "+file);
		if (cb) cb();
	});
}
Example #10
0
    '-f'
];

if (existsSync('/usr/local/include/geos_c.h')) {
    args.push('/usr/local/include/geos_c.h');
} else if (existsSync('/usr/include/geos_c.h')) {
    args.push('/usr/include/geos_c.h');
} else {
    console.error("Could not find 'geos_c.h'!");
    process.exit(-1);
}

var library_path = process.env.DYLD_LIBRARY_PATH || process.env.LD_LIBRARY_PATH;
if (library_path) {
    args.push('-L')
    args.push(process.env.LD_LIBRARY_PATH.split(':')[0])
}

cp.execFile(process.execPath, args, function(err, stdout, stderr) {
    if (stderr) {
        console.error(stderr);
    }
    if (err) {
        console.error(err.message);
        process.exit(-1);
    } else {
        console.log("sucessfully ran ffi-generate");
        fs.writeFileSync('./lib/geos.js',stdout);
        process.exit(0);
    }
});
Example #11
0
unoconv.detectSupportedFormats = function (options, callback) {
    var self = this,
        args,
        docType,
        detectedFormats = {
            document: [],
            graphics: [],
            presentation: [],
            spreadsheet: []
        },
        bin = 'unoconv';

    if (_.isFunction(options)) {
        callback = options;
        options = null;
    }

    args = ['--show'];

    if (options && options.bin) {
        bin = options.bin;
    }

    childProcess.execFile(bin, args, function (err, stdout, stderr) {
        if (err) {
            return callback(err);
        }

        // For some reason --show outputs to stderr instead of stdout
        var lines = stderr.split('\n');

        lines.forEach(function (line) {
            if (line === 'The following list of document formats are currently available:') {
                docType = 'document';
            } else if (line === 'The following list of graphics formats are currently available:') {
                docType = 'graphics';
            } else if (line === 'The following list of presentation formats are currently available:') {
                docType = 'presentation';
            } else if (line === 'The following list of spreadsheet formats are currently available:') {
                docType = 'spreadsheet';
            } else {
                var format = line.match(/^(.*)-/);

                if (format) {
                    format = format[1].trim();
                }

                var extension = line.match(/\[(.*)\]/);

                if (extension) {
                    extension = extension[1].trim().replace('.', '');
                }

                var description = line.match(/-(.*)\[/);

                if (description) {
                    description = description[1].trim();
                }

                if (format && extension && description) {
                    detectedFormats[docType].push({
                        'format': format,
                        'extension': extension,
                        'description': description,
                        'mime': mime.lookup(extension)
                    });
                }
            }
        });

        if (detectedFormats.document.length < 1 &&
            detectedFormats.graphics.length < 1 &&
            detectedFormats.presentation.length < 1 &&
            detectedFormats.spreadsheet.length < 1) {
            return callback(new Error('Unable to detect supported formats'));
        }

        callback(null, detectedFormats);
    });
};
Example #12
0
 execQueue: async.priorityQueue(function(task, callback) { execFile(task.file, task.args, callback); }),
Example #13
0
/* @flow */

var execFile = require('child_process').execFile;

// args only.
execFile('ls', ['-lh']);

// callback only.
execFile('ls', function(error, stdout, stderr) {
  console.info(stdout);
});

// options only.
execFile('wc', {timeout: 250});

// args + callback.
execFile('ls', ['-l'], function(error, stdout, stderr) {
  console.info(stdout);
});

// args + options.
execFile('ls', ['-l'], {timeout: 250});

// Put it all together.
execFile('ls', ['-l'], {timeout: 250}, function(error, stdout, stderr) {
  console.info(stdout);
});
/**
 * Created by king on 15-4-10.
 *
 * ch06.child_process_execFile_usage.js
 */
console.info("------   child_process execFile usage   ------");
console.info();
/**
 * child_process execFile
 * 查看当前目录内容
 * @type {exports}
 */
var child_process = require('child_process');   // TODO: 引入child_process模块
child_process.execFile('/bin/ls', ['-lh', '.'], function (error,stdout,stderr) {
    if (error !== null) {
        console.log('execFile error: ' + error);    // TODO: 打印输出 error
        console.log('execFile stderr: ' + stderr);    // TODO: 打印输出 error
    } else {
        console.info('当前目录内容:');
        console.info(stdout);   // TODO: 打印输出 stdout
    }
});
Example #15
0
app.post('/screenshot', function(request, response) {
  if(process.env.PASSCODE){
    if(!request.body.passcode || request.body.passcode != process.env.PASSCODE){
      return response.json(401, { 'unauthorized': ' _|_ ' });
    }
  }

  if(!request.body.address) {
    return response.json(400, { 'error': 'You need to provide the website address.' });
  }

  var filename = guid.raw() + '.png';
  var filenameFull = './images/' + filename;
  var childArgs = [
    'rasterize.js',
    format(request.body.address),
    filenameFull,
    request.body.size? request.body.size : '',
    request.body.zoom? request.body.zoom : 1
  ];

  //grap the screen
  childProcess.execFile('phantomjs', childArgs, function(error, stdout, stderr){
    console.log("Grabbing screen for: " + request.body.address);
    if(error !== null) {
      console.log("Error capturing page: " + error.message + "\n for address: " + childArgs[1]);
      return response.json(500, { 'error': 'Problem capturing page.' });
    } else {
      //load the saved file
      fs.readFile(filenameFull, function(err, temp_png_data){
        if(err!=null){
          console.log("Error loading saved screenshot: " + err.message);
          return response.json(500, { 'error': 'Problem loading saved page.' });
        }else{
          upload_params = {
            Body: temp_png_data,
            Key: guid.raw() + ".png",
            ACL: "public-read",
            Bucket: process.env.AWS_BUCKET_NAME
          };
          //start uploading
          s3.putObject(upload_params, function(err, s3_data) {
            if(err!=null){
              console.log("Error uploading to s3: " + err.message);
              return response.json(500, { 'error': 'Problem uploading to S3.' + err.message });
            }else{
              //clean up and respond
              fs.unlink(filenameFull, function(err){}); //delete local file
              var s3Region = process.env.AWS_REGION? 's3-' + process.env.AWS_REGION : 's3'
              var s3Url = 'https://' + s3Region + ".amazonaws.com/" + process.env.AWS_BUCKET_NAME +
              '/' + upload_params.Key;

              if (request.body.redirect == 'true') {
                return response.redirect(302, s3Url);
              } else {
                return response.json(200, { 'url': s3Url });
              }
            }
          });
        }
      });
    }
  });
});
Example #16
0
 beforeEach(function(done){
   var db = server.app.environment.MONGO_URL.split('/')[3];
   CP.execFile(Path.join(__dirname, '../../../../scripts/clean-db.sh'), [db], {cwd: Path.join(__dirname, '../../../../scripts')}, function(){
     done();
   });
 });
Example #17
0
    const {hash} = options;

    if (hash == null) {
      callback(null, {error: 'Hash must be defined'});
      return;
    }
    const selectedTorrent = torrentService.getTorrent(hash);
    try {
      child_process.execFile('mediainfo', [selectedTorrent.basePath], {maxBuffer: 1024 * 2000}, function(
        error,
        stdout,
        stderr
      ) {
        if (error) {
          callback(null, {error});
          return;
        }

        if (stderr) {
          callback(null, {error: stderr});
          return;
        }

        callback({output: stdout});
      });
    } catch (childProcessError) {
      callback(null, {error: childProcessError});
    }
  },
};
Example #18
0
 return Promise.fromCallback((cb) => {
   childProcess.execFile('file', ['--mime-type', file], cb)
 })
assert.throws(function() { execFile(cmd, n, o, s); }, invalidArgValueError);
Example #20
0
 return new Promise((resolve, reject) => {
   execFile(file, args, options, (err, stdout, stderr) => {
     if (err) return reject(err)
     resolve({stdout, stderr})
   })
 })
Example #21
0
File: capture.js Project: rapee/boo
  return (hook, next) => {
    const url = hook.data.url;

    if (!url) {
      next(new errors.BadRequest('Missing required url'));
      return;
    }

    // PhatomJS
    const path = require('path');
    const childProcess = require('child_process');
    const phantomjs = require('phantomjs-prebuilt');
    const binPath = phantomjs.path;
    const childArgs = [
      path.join(__dirname, '../../../phantomjs', 'capture.js'),
      url
    ];

    const start = Date.now();
    childProcess.execFile(binPath, childArgs, (err, stdout, stderr) => {
      if (err) return next(err);
      if (stderr) return next(new Error(stderr));
      // capture success
      let data;
      try {
        data = JSON.parse(stdout);
      } catch (err2) {
        err = err2;
      }
      // unrecognized data
      if (!data || err) {
        hook.data = null;
        next(new errors.GeneralError(err));
      } else if (data.response.status >= 200 && data.response.status < 300) {
        // success
        hook.data = {
          url: url,
          mime: 'text/html',
          content: data.html,
          time: Date.now() - start,
          created_at: new Date
        };
        next();
      } else {
        // fail
        hook.data = null;
        if (data.response.status === 400) {
          next(new errors.BadRequest({ code: data.response.status }));
        } else if (data.response.status === 401) {
          next(new errors.NotAuthenticated({ code: data.response.status }));
        } else if (data.response.status === 403) {
          next(new errors.Forbidden({ code: data.response.status }));
        } else if (data.response.status === 404) {
          next(new errors.NotFound({ code: data.response.status }));
        } else if (data.response.status === 408) {
          next(new errors.Timeout({ code: data.response.status }));
        } else if (data.response.status === 503) {
          next(new errors.Unavailable({ code: data.response.status }));
        } else {
          next(new errors.GeneralError({ code: data.response.status }));
        }
      }
    });
  };
function csignkeypair(callback) {
  execFile(path.resolve(__dirname, 'csign-keypair'), [], function(err, stdout) {
    if (err) throw err;
    callback(stdout.toString('utf8'));
  });
}
Example #23
0
function archiveGitRemote (p, u, co, origUrl, cb) {
  var git = npm.config.get("git")
  var archive = [ "fetch", "-a", "origin" ]
  var resolve = [ "rev-list", "-n1", co ]
  var env = gitEnv()

  var errState = null
  var n = 0
  var resolved = null
  var tmp

  exec(git, archive, {cwd: p, env: env}, function (er, stdout, stderr) {
    stdout = (stdout + "\n" + stderr).trim()
    if (er) {
      log.error("git fetch -a origin ("+u+")", stdout)
      return cb(er)
    }
    log.verbose("git fetch -a origin ("+u+")", stdout)
    tmp = path.join(npm.tmp, Date.now()+"-"+Math.random(), "tmp.tgz")
    resolveHead()
  })

  function resolveHead () {
    exec(git, resolve, {cwd: p, env: env}, function (er, stdout, stderr) {
      stdout = (stdout + "\n" + stderr).trim()
      if (er) {
        log.error("Failed resolving git HEAD (" + u + ")", stderr)
        return cb(er)
      }
      log.verbose("git rev-list -n1 " + co, stdout)
      var parsed = url.parse(origUrl)
      parsed.hash = stdout
      resolved = url.format(parsed)

      // https://github.com/isaacs/npm/issues/3224
      // node incorrectly sticks a / at the start of the path
      // We know that the host won't change, so split and detect this
      var spo = origUrl.split(parsed.host)
      var spr = resolved.split(parsed.host)
      if (spo[1].charAt(0) === ':' && spr[1].charAt(0) === '/')
        spr[1] = spr[1].slice(1)
      resolved = spr.join(parsed.host)

      log.verbose('resolved git url', resolved)
      next()
    })
  }

  function next () {
    mkdir(path.dirname(tmp), function (er) {
      if (er) return cb(er)
      var gzip = zlib.createGzip({ level: 9 })
      var git = npm.config.get("git")
      var args = ["archive", co, "--format=tar", "--prefix=package/"]
      var out = fs.createWriteStream(tmp)
      var env = gitEnv()
      cb = once(cb)
      var cp = spawn(git, args, { env: env, cwd: p })
      cp.on("error", cb)
      cp.stderr.on("data", function(chunk) {
        log.silly(chunk.toString(), "git archive")
      })

      cp.stdout.pipe(gzip).pipe(out).on("close", function() {
        addLocalTarball(tmp, function(er, data) {
          if (data) data._resolved = resolved
          cb(er, data)
        })
      })
    })
  }
}
Example #24
0
exports.optimage = function(inputFile, outputFile, level, verbose, done){

    var binPath= '';
    var args= [];

    outputFile = outputFile || inputFile;

    switch ( path.extname(inputFile) ){

        // 1. Basic optimisation
        // optipng xx.png -out xx2.png
        // optipng xx.png -dir ./img
        // default -o2

        // TODO
        // 2. Removing unnecessary chunks
        // pngcrush -q -rem gAMA -rem alla -rem text image.png image.crushed.png
        // 3. Reducing the colour palette
        // pngnq -f -n 32 -s 3 image.png
        // 4. Re-compressing final image
        // advpng -z -4 image.png
        case '.png':
            binPath = require('optipng-bin').path;
            // OptiPNG can't overwrite without creating a backup file
            // https://sourceforge.net/tracker/?func=detail&aid=3607244&group_id=151404&atid=780913
            if (path.resolve(outputFile) !== path.resolve(inputFile) && file.exists(outputFile)) {
                file.delete(outputFile);
            }

            args.push('-strip', 'all', inputFile, "-out", outputFile, '-o', level||2 );
            break;

        // jpegtran [switches] inputfile outputfile
        case '.jpg':
        case '.jpeg':
            binPath = require('jpegtran-bin').path;
            args.push('-copy', 'none', '-optimize','-outfile', outputFile, inputFile );

            break;

        default:
            return;
    }

    // command Dir
    exports.debug(binPath, args.join(" "));

    var originalSize = fs.statSync(inputFile).size;

    execFile(binPath, args, function(err, stdout, stderr) {

        if (verbose) {
            stdout && console.log(stdout);
            stderr && console.log(stderr);
        }

        var saved = originalSize - fs.statSync(outputFile).size;

        // TODO: check or create target build dir
        if (stderr.indexOf('already optimized') !== -1 || saved < 10) {
            exports.log(inputFile.grey, "(already optimized)", ">".grey, outputFile.grey);
        }else{
            exports.log(inputFile.grey, "(saved "+ saved+ "Bytes)", ">".grey, outputFile.grey);
        }

        done();
    });

};
Example #25
0
 check_bat(function (bat) {
   exec(bat, function (err) {
     console.log(err);
   });
 });
/**
 * Calls youtube-dl with some arguments and the `callback`
 * gets called with the output.
 *
 * @param {String|Array.<String>}
 * @param {Array.<String>} args
 * @param {Array.<String>} args2
 * @param {Object} options
 * @param {Function(!Error, String)} callback
 */
function call(urls, args1, args2, options, callback) {
  'use strict';
  var args = args1;
  if (args2) {
    args = args.concat(util.parseOpts(args2));
  }
  options = options || {};

  if (urls !== null) {
    if (typeof urls === 'string') {
      urls = [urls];
    }

    for (var i = 0; i < urls.length; i++) {
      var video = urls[i];
      if (isYouTubeRegex.test(video)) {
        // Get possible IDs.
        var details = url.parse(video, true);
        var id = details.query.v || '';
        if (id) {
          args.push('http://www.youtube.com/watch?v=' + id);
        } else {
          // Get possible IDs for youtu.be from urladdr.
          id = details.pathname.slice(1).replace(/^v\//, '');
          if (id || id === 'playlist') {
            args.push(video);
          }
        }
      } else {
        args.push(video);
      }
    }
  }

  // Call youtube-dl.
  execFile(ytdlBinary, args, options, function done(err, stdout, stderr) {
    if (err) { return callback(err); }

    if (stderr) {
      // Try once to download video if no subtitles available
      if (!options.nosubs && isNoSubsRegex.test(stderr)) {
        var i;
        var cleanupOpt = args2;

        for (i = cleanupOpt.length - 1; i >= 0; i--) {
          if (subsRegex.test(cleanupOpt[i])) { cleanupOpt.splice(i, 1); }
        }

        options.nosubs = true;

        return call(video, args1, cleanupOpt, options, callback);

      }

      if (isDebug.test(stderr) && args.indexOf('--verbose') > -1) {
        console.log('\n' + stderr);
      } else if (isWarning.test(stderr)) {
        console.warn(stderr);
      } else {
        return callback(new Error(stderr.slice(7)));
      }

    }

    var data = stdout.trim().split(/\r?\n/);
    callback(null, data);
  });

}
Example #27
0
 t.test('raw TAP > TAP consumer > summary', function(t) {
   var args = [bin, '--no-tap', useConsole]
   execFile(node, args, assertDirectivesSummary.bind(this, t))
 })
Example #28
0
var path = require("path");
var fs = require("fs");
var swig = require("swig");
var childProcess = require("child_process");
var phantomjs = require("phantomjs");
var phantomBinPath = phantomjs.path;
var _ = require("underscore");

var cvJson = fs.readFileSync("cv.json");
var cv = JSON.parse(cvJson);
console.log("CV %j", cv);

var html = swig.renderFile("cv.template", cv);
console.log(html);

fs.writeFileSync("cv.html", html);

var phantomArgs = [
	path.join(__dirname, "rasterize.js"),
	"cv.html",
	"cv.pdf",
	"A4"
];
childProcess.execFile(phantomBinPath, phantomArgs, function(err, stdout, stderr) {
	console.log("OK");
});
Example #29
0
 beforeEach(function(done){
   cp.execFile(__dirname + '/../scripts/clean-db.sh', [db], {cwd:__dirname + '/../scripts'}, function(err, stdout, stderr){
     done();
   });
 });
Example #30
0
 beforeEach(function(done){
   cp.execFile(__dirname + '/../scripts/freshdb.sh', [db], {cwd:__dirname + '/../scripts'}, function(){
     done();
   });
 });