Example #1
0
test('generate a nonempty PDF from ipsum.md', function (t) {
  t.plan(4)

  tmp.file({postfix: '.pdf'}, function (er, tmpPdfPath, tmpPdfFd) {
    t.ifError(er)
    fs.closeSync(tmpPdfFd)

    markdownpdf().from(path.join(__dirname, '/fixtures/ipsum.md')).to(tmpPdfPath, function (er) {
      t.ifError(er)

      // Read the file
      fs.readFile(tmpPdfPath, {encoding: 'utf8'}, function (er, data) {
        t.ifError(er)
        // Test not empty
        t.ok(data.length > 0)
        t.end()
      })
    })
  })
})
Example #2
0
  it("should save the credentials.json as a formatted JSON when adding", function(done) {
    args.push("adduser");
    args.push("myuser");
    args.push("mypass");
    args.push("--credentials");

    tmp.file(function (err, path, fd) {
      if (err) {
        done(err);
        return;
      }

      args.push(path);
      mosca.cli(args, function () {
        var content = fs.readFileSync(path);
        expect(JSON.stringify(JSON.parse(content), null, 2)).to.equal(content.toString('utf8'));
        done();
      });
    });
  });
Example #3
0
File: run.js Project: Tairyu/jsfmt
    tmp.file(function(err, pathA, fdA) {
      if (err) {
        console.error(err);
        return;
      }
      fs.writeSync(fdA, originalJavascript);

      tmp.file(function(err, pathB, fdB) {
        if (err) {
          console.error(err);
          return;
        }
        fs.writeSync(fdB, formattedJavascript);

        diff(pathA, pathB, function(err, stdout, stderr) {
          if (stdout) console.log(stdout);
          if (stderr) console.log(stderr);
        });
      });
    });
Example #4
0
		// Create temporary config file if needed
		function configContext (next) {
			if (options.raw) {
				// Tmp file is only available within the context of this function
				tmp.file({ prefix: '_config.', postfix: '.yml' }, function (err, path, fd) {

					rawConfigFile = path;

					if (err) {
						grunt.fail.warn(err);
					}

					// Write raw to file
					fs.writeSync(fd, new Buffer(options.raw), 0, options.raw.length);
					next();
				});
			}
			else {
				next();
			}
		}
Example #5
0
  it("should add an user to an authorization file", function(done) {
    args.push("adduser");
    args.push("myuser");
    args.push("mypass");
    args.push("--credentials");

    tmp.file(function (err, path, fd) {
      if (err) {
        done(err);
        return;
      }

      args.push(path);
      mosca.cli(args, function () {
        var content = JSON.parse(fs.readFileSync(path));
        expect(content).to.have.property("myuser");
        done();
      });
    });
  });
test("generate a nonempty PDF from ipsum.md", function (t) {
  t.plan(4)

  tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath, tmpPdfFd) {
    t.ifError(er)
    fs.close(tmpPdfFd)

    markdownpdf().from(__dirname + "/fixtures/ipsum.md").to(tmpPdfPath, function (er) {
      t.ifError(er)

      // Read the file
      fs.readFile(tmpPdfPath, {encoding: "utf8"}, function (er, data) {
        t.ifError(er)
        // Test not empty
        t.ok(data.length > 0)
        t.end()
      })
    })
  })
})
Example #7
0
exports.create_cert = function (opts, reqPath, caKeyPath, caCertPath, extPath, cb) {
  tmp.file(opts, function tmpFileCb(err, path) {
    if (err) return cb(err);
    var setDays = '';
    if (exports.days && exports.days === parseInt(exports.days, 10)) {
      setDays = ' -days ' + exports.days;
    }
    child.exec('openssl x509 -req -in ' + reqPath + ' -CAkey ' + caKeyPath + ' -CA ' +
                caCertPath + ' -out ' + path + ' -CAcreateserial' +
                ' -extensions v3_ca -extfile ' + extPath + setDays,
                function execCb(err) {
      if (err) return cb(err);
      child.exec('openssl x509 -noout -in ' + path + ' -fingerprint -hash',
                  function statsCb(err, stdout) {
        output = stdout.toString().split(/\n/);
        cb(err, path, output[0], output[1]);
      });
    });
  });
}
Example #8
0
  tmp.file({postfix: ".html"}, function (er, tmpHtmlPath, tmpHtmlFd) {
    if (er) return outputStream.emit("error", er)
    fs.close(tmpHtmlFd)

    // Create tmp file to save PDF to
    tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath, tmpPdfFd) {
      if (er) return outputStream.emit("error", er)
      fs.close(tmpPdfFd)

      var htmlToTmpHtmlFile = fs.createWriteStream(tmpHtmlPath)

      htmlToTmpHtmlFile.on("finish", function () {
        // Invoke phantom to generate the PDF
        var childArgs = [
            path.join(__dirname, "..", "lib-phantom", "html5-to-pdf.js")
          , tmpHtmlPath
          , tmpPdfPath
          , opts.runningsPath
          , opts.cssPath
          , opts.highlightCssPath
          , opts.paperFormat
          , opts.paperOrientation
          , opts.paperBorder
          , opts.renderDelay
          , opts.template
          , opts.jsPath
        ]

        childProcess.execFile(opts.phantomPath, childArgs, function(er, stdout, stderr) {
          //if (stdout) console.log(stdout)
          //if (stderr) console.error(stderr)
          if (er) return outputStream.emit("error", er)
          fs.createReadStream(tmpPdfPath).pipe(outputStream)
        })
      })

      // Setup the pipeline
      inputStream.pipe(opts.preProcessHtml()).pipe(htmlToTmpHtmlFile)
      inputStream.resume()
    })
  })
Example #9
0
Grabber.prototype.download = function(bucket, region, remoteImagePath, callback) {
	var _this = this,
		extension = remoteImagePath.split('.').pop();

	tmp.file({dir: config.get('tmpDir'), postfix: "." + extension}, function(err, localImagePath, fd) {

		if (err) return callback(err);

		fs.close(fd, function() {
			_this.logger.info('downloading', remoteImagePath, 'from s3 to local file', localImagePath);

			var stream = fs.createWriteStream(localImagePath);

			if (remoteImagePath.match(/https?:\/\//)) { // we are thumbnailing a remote image.
				_this.getFileHTTP(remoteImagePath, localImagePath, stream, callback);
			} else { // we are thumbnailing an Object in our thumbnail S3 bucket.
				_this.getFileS3(bucket, region, remoteImagePath, localImagePath, stream, callback);
			}
		}); // close immediately, we do not use this file handle.
	});
};
Example #10
0
  before(function(done) {
    tmp.setGracefulCleanup();

    // set up account
    tmp.file(function(err, tmpFile) {
      should.not.exist(err);
      config.account.file = tmpFile;
      var sourceFile = path.join(__dirname, '..', 'account', 'accounts.json');
      helpers.copyFile(sourceFile, tmpFile, function(err) {
        should.not.exist(err);

        // set up project dir
        tmp.dir({ unsafeCleanup: true }, function(err, path) {
          should.not.exist(err);
          tmpDir = path;
          process.chdir(tmpDir);
          done();
        });
      });
    });
  });
Example #11
0
Grabber.prototype.download = function(remoteImagePath, callback) {
	var _this = this,
		extension = remoteImagePath.split('.').pop();

	tmp.file(function(err, localImagePath, fd) {

		console.log('downloading', remoteImagePath, 'from s3 to local file', localImagePath);

		if (err) {
			callback(err);
			return;
		}
		var stream = fs.createWriteStream(localImagePath);

    if (remoteImagePath.match(/https?:\/\//)) { // we are thumbnailing a remote image.
      _this.getFileHTTP(remoteImagePath, localImagePath, stream, callback);
    } else { // we are thumbnailing an Object in our thumbnail S3 bucket.
		  _this.getFileS3(remoteImagePath, localImagePath, stream, callback);
    }
	});
};
Example #12
0
module.exports = function(certDir, cb) {
  tmp.file(function(err, zipPath, fd) {
    zipPath += '.zip';
    var zip = spawn('zip', ['-r', zipPath, '.'], {
      cwd: certDir
    });

    zip.stderr.on('data', function(data) {
      log.error('zip STDERR: ' + data);
    });

    zip.on('close', function(code) {
      if (0 !== code) {
        log.error('zip finished with an error, exit code:', code);
        cb(new Error('zip finished with an error, exit code:', code));
      } else {
        cb(null, zipPath);
      }
    });
  });
};
Example #13
0
File: new.js Project: jacobk/werk
 return new RSVP.Promise(function(resolve, reject) {
   if (didConfirm) {
     tmp.file(function(err, path, fd) {
       if (err) {
         return reject({
           reason: 'Unable to create tmp file',
           help: err
         });
       }
       fs.writeSync(fd, pullRequest.body);
       editor(path, function(code, sig) {
         // TODO: Handle if nothing actually saved + other errors
         pullRequest.body = fs.readFileSync(path).toString();
         logger.log.writelns('Successfuly edited');
         return resolve(pullRequest);
       });
     });
   } else {
     resolve(pullRequest);
   }
 });
 return new Promise(function(resolve, reject) {
   tmp.file({prefix: fileName}, function(err, path) {
     if (err) {
       console.log('Failed to create tmp file', err);
       reject(err);
     } else {
       var stream = fs.createWriteStream(path);
       console.log('fetching file from', props.build_url);
       https.get(props.build_url, function(res) {
         upload(fileName, stream, function(err, data) {
           console.log('RETURN FROM S3', err, data);
           if (err) {
             resolve(err);
           } else {
             resolve(data);
           }
         });
       });
     }
   });
 });
Example #15
0
      zipEvents.on('finished', function(files){

        files.forEach(function(file){
          zip.file(file.name, file.contents);
        });

        var archive = zip.generate({ base64: false, compression: 'DEFLATE' });
        tmp.file({ dir: dirPath, prefix: Date.now(), postfix: '.zip' }, function _tempZipFileCreated(fileErr, filePath, fileDescriptor){
          if (fileErr) return next(fileErr);
          console.log('Created temp file: ' + filePath);
          fs.writeFile(filePath, archive, { encoding: 'binary' }, function (fileWriteErr) {
            if (fileWriteErr) return next(fileWriteErr);
            var filename = 'honda-videos-' + Date.now() +'.zip';
            var contentType = mime.lookup(filePath);
            var data = fs.createReadStream(filePath);
            res.setHeader('Content-disposition', 'attachment; filename=' + filename);
            res.setHeader('Content-type', contentType);
            data.pipe(res);
          });
        });
      });
Example #16
0
        exec.getNpmGlobalPath(function(npmPath){
            jsDocArgs.template = options.template ? options.template : path.join(npmPath, DEFAULT_TEMPLATE); 

            docOptions.opts = fis.util.merge(jsDocArgs, docOptions.opts || {});

            //Generate the jsdoc conf.json
            tmp.setGracefulCleanup();
            tmp.file(function (err, _path, fd) {
                if (err) {
                    throw err;
                }

                //Write the jsDoc configuration
                fs.writeSync(fd, JSON.stringify(docOptions));
                fs.fsyncSync(fd);

                exec.spawn(sources, npmPath, {
                    "configure": _path,
                    "verbose": !!options.verbose
                }, function(execChild){
                    //logs
                    execChild.stdout.on("data", function (data){
                        fis.log.debug("jsDoc output : " + data);
                    });
                    execChild.stderr.on("data", function(data){
                        console.error(data);
                    });
                    execChild.on("error", function(data){
                        console.error("[Can be ignored] An error occurs in jsDoc process:\n" + data);
                    });
                    execChild.on("exit", function(code){
                        if (code === 0){
                            console.log("Documentation generated to " + path.resolve(docOptions.opts.destination));
                        }else{
                            console.error("Documentation generated failed. Error code: " + code);
                        }
                    });
                }); 
            });
        });
Example #17
0
  it("should add an user specifying the authorizeSubscribe pattern", function(done) {
    args.push("adduser");
    args.push("myuser");
    args.push("mypass");
    args.push("--authorize-subscribe");
    args.push("hello/**/*");
    args.push("--credentials");

    tmp.file(function (err, path, fd) {
      if (err) {
        done(err);
        return;
      }

      args.push(path);
      mosca.cli(args, function () {
        var content = JSON.parse(fs.readFileSync(path));
        expect(content.myuser).to.have.property("authorizeSubscribe", "hello/**/*");
        done();
      });
    });
  });
Example #18
0
    return new Promise((resolve, reject) => {
      if (currentFilePath instanceof Readable) {

        // currentFilePath is a GridReadStream
        tmp.file({dir: directory, keep: true}, (err, tempFilePath) => {
          if (err) {
            return reject(err);
          }

          let writeStream = createWriteStream(tempFilePath);
          currentFilePath.pipe(writeStream);

          writeStream.on('finish', function() {
            return resolve({name: currentFile.name, path: tempFilePath});
          });

          writeStream.on('error', reject);
        });
      } else {
        return resolve({name: currentFile.name, path: currentFilePath});
      }
    });
Example #19
0
 tmp.file({postfix: '.' + ext}, function (err, srcPath, srcFd, cleanSrcTmp) {
   if (err) {
     return cb(err);
   }
   tmp.file({postfix: '.' + ext}, function (err, destPath, destFd, cleanDestTmp) {
     if (err) {
       return cb(err);
     }
     fs.writeFile(srcPath, buf, function (err) {
       if (err) {
         return cb(err);
       }
       var resize;
       if (height) {
         resize = gm(srcPath).resize(width, height, '^').gravity('Center').crop(width, height);
       } else {
         resize = gm(srcPath).resize(width);
       }
       resize.interlace('plane').write(destPath, function (err) {
         if (err) {
           return cb(err);
         }
         fs.readFile(destPath, function (err, res) {
           cb(null, res);
           try {
             cleanSrcTmp();
             cleanDestTmp();
           } catch (e) {
             console.error(e);
           }
           fs.close(srcFd, function () {
           });
           fs.close(destFd, function () {
           });
         });
       });
     });
   });
 });
Example #20
0
function concatFiles(filePaths, cb) {
    _$jscoverage_done("lib/markdown-pdf.js", 79);
    tmp.file(function(er, tmpMdPath, tmpMdFd) {
        _$jscoverage_done("lib/markdown-pdf.js", 80);
        if (_$jscoverage_done("lib/markdown-pdf.js", 80, er)) {
            _$jscoverage_done("lib/markdown-pdf.js", 80);
            return cb(er);
        }
        _$jscoverage_done("lib/markdown-pdf.js", 81);
        fs.close(tmpMdFd);
        _$jscoverage_done("lib/markdown-pdf.js", 83);
        var writeStream = fs.createWriteStream(tmpMdPath);
        function iterate() {
            _$jscoverage_done("lib/markdown-pdf.js", 86);
            if (_$jscoverage_done("lib/markdown-pdf.js", 86, filePaths.length === 0)) {
                _$jscoverage_done("lib/markdown-pdf.js", 87);
                writeStream.end();
                _$jscoverage_done("lib/markdown-pdf.js", 88);
                return cb(null, tmpMdPath);
            }
            _$jscoverage_done("lib/markdown-pdf.js", 91);
            var path = filePaths.shift();
            _$jscoverage_done("lib/markdown-pdf.js", 92);
            var readStream = fs.createReadStream(path);
            _$jscoverage_done("lib/markdown-pdf.js", 93);
            readStream.on("end", function() {
                _$jscoverage_done("lib/markdown-pdf.js", 94);
                iterate();
            });
            _$jscoverage_done("lib/markdown-pdf.js", 96);
            readStream.pipe(writeStream, {
                end: false
            });
        }
        _$jscoverage_done("lib/markdown-pdf.js", 99);
        iterate();
    });
}
Example #21
0
app.post('/', function(req, res) {
    
    // output format (pdf or png )

    tmp.file({postfix: '.svg'}, function _tempFileCreated(err, inputFilePath, fd) {

        if (err) {
            res.json(500, err);
        } else {
            fs.writeFile(inputFilePath, req.body.data, function(err) {
                if (err) {
                    res.json(500, err);
                } else {
                    tmp.file({postfix: '.'+req.body.outputFormat}, function _tempFileCreated(err, outputFilePath, fd) {
                        if (err) {
                            res.json(500, err);
                        } else {
                            var cmd = "rsvg-convert -z 5 --background-color white -a";
                            cmd += " -f "+req.body.outputFormat;
                            cmd += " -o "+outputFilePath;
                            cmd += " "+inputFilePath;

                            exec(cmd, function (error, stdout, stderr) {
                                
                                if (error !== null) {
                                    res.json(500, error);
                                } else {
                                    res.attachment(outputFilePath);
                                    res.sendfile(outputFilePath);
                                }
                            });
                        }
                    });
                }
            });
        }
    });
});
Example #22
0
  tmp.file({postfix: '.pdf'}, function (er, tmpPdfPath0, tmpPdfFd0) {
    t.ifError(er)
    fs.closeSync(tmpPdfFd0)

    tmp.file({postfix: '.pdf'}, function (er, tmpPdfPath1, tmpPdfFd1) {
      t.ifError(er)
      fs.closeSync(tmpPdfFd1)

      markdownpdf().from.paths(files).to.paths([tmpPdfPath0, tmpPdfPath1], function (er) {
        t.ifError(er)

        // Read the file
        var content0 = fs.readFileSync(tmpPdfPath0, {encoding: 'utf8'})
        var content1 = fs.readFileSync(tmpPdfPath1, {encoding: 'utf8'})

        t.ok(content0.length > 0)
        t.ok(content1.length > 0)
        t.ok(content0.length !== content1.length)

        t.end()
      })
    })
  })
Example #23
0
 'resultBuffer': ['originalBuffer', 'originalDimensions', function (next, data) {
   if (resizeCondition(data.originalDimensions)) {
     tmp.file({postfix: '.jpg'}, function (err, sourcePath, fd, removeSourceTmpFn) {
       if (err) { return next(err); }
       tmp.file({postfix: '.jpg'}, function (err, destinationPath, fd, removeDestinationTmpFn) {
         if (err) { return next(err); }
         fs.writeFile(sourcePath, data.originalBuffer, function (err) {
           if (err) { return next(err); }
           gm(sourcePath).interlace('plane').resize(1000, 1000).write(destinationPath, function (err) {
             if (err) { return next(err); }
             fs.readFile(destinationPath, function (err, res) {
               removeSourceTmpFn();
               removeDestinationTmpFn();
               next(null, res);
             });
           });
         });
       });
     });
   } else {
     next(null, data.originalBuffer);
   }
 }],
Example #24
0
  grunt.registerMultiTask('compass', 'Compile Compass to CSS', function () {
    var options = this.options();
    var cb = this.async();
    var raw = options.raw;
    // get the array of arguments for the compass command
    var args = compass.buildArgsArray(options);

    if (raw) {
      tmp.file(function (err, path, fd) {
        if (err) {
          grunt.fail.fatal(err);
        }

        // Dynamically create config.rb as a tmp file for the `raw` content
        fs.writeSync(fd, new Buffer(raw), 0, raw.length);

        args.push('--config', path);
        compile(args, cb);
      });
    } else {
      compile(args, cb);
    }
  });
Example #25
0
    tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath0, tmpPdfFd0) {
      assert.ifError(er)
      fs.close(tmpPdfFd0)

      tmp.file({postfix: ".pdf"}, function (er, tmpPdfPath1, tmpPdfFd1) {
        assert.ifError(er)
        fs.close(tmpPdfFd1)

        markdownpdf().from.paths(files).to.paths([tmpPdfPath0, tmpPdfPath1], function (er) {
          assert.ifError(er)

          // Read the file
          var content0 = fs.readFileSync(tmpPdfPath0, {encoding: "utf8"})
          var content1 = fs.readFileSync(tmpPdfPath1, {encoding: "utf8"})

          assert.ok(content0.length > 0)
          assert.ok(content1.length > 0)
          assert.ok(content0.length != content1.length)

          done()
        })
      })
    })
Example #26
0
/**
 * Concatenate files into a single file.
 *
 * @param  {Array} filePaths Paths to files to concatenate together
 * @param  {Function} cb Callback function invoked when the files have been concatenated. Passed Error and a String
 * path to the new file.
 */
function concatFiles (filePaths, cb) {
  tmp.file(function (er, tmpMdPath, tmpMdFd) {
    if (er) return cb(er)
    fs.close(tmpMdFd)

    var writeStream = fs.createWriteStream(tmpMdPath)

    function iterate () {
      if (filePaths.length === 0) {
        writeStream.end();
        return cb(null, tmpMdPath)
      }

      var path = filePaths.shift()
      var readStream = fs.createReadStream(path)
      readStream.on('end', function () {
        iterate()
      })
      readStream.pipe(writeStream, { end: false })
    }

    iterate()
  })
}
Example #27
0
  http.get(options, function(res) {
    tmp.file({ prefix: 'task-', postfix: '.gz' }, function _tempFileCreated(err, path, fd) {
      if (err) {
        self._error(err)
      } else {
        var file = fs.createWriteStream(path)
        res.on('data', function(chunk) {
          file.write(chunk)

        }).on('end', function() {
            file.end()
            self.setStatus('downloaded')
            var child = exec('gunzip ' + path, function (error, stdout, stderr) {
              if (error != null) {
                self._error(error)
              } else {
                self.setStatus('decompressed')
                self._streamLocalFile(path.substr(0, path.length - 3))
              }
            })
          })
      }
    })
  }).on('error', function(err) {
Example #28
0
    fs.exists(path, function (exists) {
      if (exists) {
        tmp.file(function _tempFileCreated(tmperr, tmpath, fd, cleanupCallback) {
          if (tmperr) return console.log(tmperr);

          fs.readFile(path, 'utf8', function (readerr, filedata) {
            if (readerr) { return console.log(readerr); }

            fs.writeFile(tmpath, '<dreem>' + filedata + '</dreem>', function (writeerr) {
              if (writeerr) return console.log(writeerr);

              validate(tmpath, function(results) {
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify(results));
                cleanupCallback();
              });
            });
          });
        });
      } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end(path + ' not found');
      }
    });
Example #29
0
 it('should write/read/remove from a buffer', function(done) {
   var filename = 'MyBuffer';
   var fileContent =  'Hello World';
   tmp.setGracefulCleanup();
   tmp.file(function _tempFileCreated(err, path) {
     assert.ifError(err);
     bucket.write(filename, fileContent, function(err, fileObject) {
       assert.ifError(err);
       assert(fileObject);
       bucket.createReadStream(filename)
           .pipe(fs.createWriteStream(path))
           .on('error', done)
           .on('finish', function() {
             bucket.remove(filename, function(err) {
               assert.ifError(err);
               fs.readFile(path, function(err, data) {
                 assert.equal(data, fileContent);
                 done();
               });
             });
           });
     });
   });
 });
Example #30
0
function tilesToIndexesBinary(schema_path, tiles_path, binary_path, next) { // next(error)
	var schema = new Schema(schema_path);



	tmp_.file({ postfix: '.indexes.json'}, function(error, indexes_path, fd, cleanupCallback) {
		if (error) { return next(error); }



		tilesToIndexesFile(tiles_path, indexes_path, function (error) {
			if (error) {
				cleanupCallback();
				return next(error); 
			}

			schema.encode(indexes_path, binary_path, function (error) {
				cleanupCallback();
				if (error) { return next(error); }
				return next();
			});
		});
	});
}