render.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var fs = require('fs'),
  2. chalk = require('chalk'),
  3. sass = require('./'),
  4. path = require('path'),
  5. mkdirp = require('mkdirp');
  6. /**
  7. * Render
  8. *
  9. * @param {Object} options
  10. * @param {Object} emitter
  11. * @api public
  12. */
  13. module.exports = function(options, emitter) {
  14. var renderOptions = {
  15. imagePath: options.imagePath,
  16. includePaths: options.includePath,
  17. omitSourceMapUrl: options.omitSourceMapUrl,
  18. indentedSyntax: options.indentedSyntax,
  19. outFile: options.dest,
  20. outputStyle: options.outputStyle,
  21. precision: options.precision,
  22. sourceComments: options.sourceComments,
  23. sourceMapEmbed: options.sourceMapEmbed,
  24. sourceMapContents: options.sourceMapContents,
  25. sourceMap: options.sourceMap,
  26. importer: options.importer
  27. };
  28. if (options.data) {
  29. renderOptions.data = options.data;
  30. } else if (options.src) {
  31. renderOptions.file = options.src;
  32. }
  33. renderOptions.success = function(result) {
  34. var todo = 1;
  35. var done = function() {
  36. if (--todo <= 0) {
  37. emitter.emit('done');
  38. }
  39. };
  40. if (options.stdout || (!options.dest && !process.stdout.isTTY) || options.stdin) {
  41. emitter.emit('log', result.css);
  42. return done();
  43. }
  44. emitter.emit('warn', chalk.green('Rendering Complete, saving .css file...'));
  45. mkdirp(path.dirname(options.dest), function(err) {
  46. if (err) {
  47. return emitter.emit('error', chalk.red(err));
  48. }
  49. fs.writeFile(options.dest, result.css, function (err) {
  50. if (err) {
  51. return emitter.emit('error', chalk.red(err));
  52. }
  53. emitter.emit('warn', chalk.green('Wrote CSS to ' + options.dest));
  54. emitter.emit('write', err, options.dest, result.css);
  55. done();
  56. });
  57. });
  58. if (options.sourceMap) {
  59. todo++;
  60. fs.writeFile(options.sourceMap, result.map, function(err) {
  61. if (err) {
  62. return emitter.emit('error', chalk.red('Error' + err));
  63. }
  64. emitter.emit('warn', chalk.green('Wrote Source Map to ' + options.sourceMap));
  65. emitter.emit('write-source-map', err, options.sourceMap, result.sourceMap);
  66. done();
  67. });
  68. }
  69. emitter.emit('render', result.css);
  70. };
  71. renderOptions.error = function(error) {
  72. emitter.emit('error', chalk.red(JSON.stringify(error, null, 2)));
  73. };
  74. sass.render(renderOptions);
  75. };