Send request to back end to saved file.
After the file has been successfully saved, navigates to "Display" mode of the content.
@returns {Promise} - <code>LRepConnector</code> "saveFiles" promise
@private
499703
function (sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName) {
			return LRepConnector.saveFile(sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName).then(this._navToDisplayMode.bind(this));
		}
657236
function writeFile(file, contents) {
	return new Promise(
		(resolve, reject) => {
			fs.writeFile(
				file, contents, error => {
					if (error) {
						reject(error);
					} else {
						// console.log('writeFile', [file, contents]);
						resolve(contents);
					}
				}
			)
		}
	);
}
27499
function () {
            var self = this;
            if (this._dirty) {
                self._dirty = false;
                return this.storage.save(this.data);
            } else {
                return (new $.Deferred()).resolve().promise();
            }
        }
174494
function captureScreenshot (chromy, filePath_, selector, selectorMap, config, selectors) {
  return new Promise(function (resolve, reject) {
    // VIEWPORT screenshot
    if (selector === VIEWPORT_SELECTOR || selector === BODY_SELECTOR) {
      chromy
        .screenshot()
        .result(buffer => {
          return saveViewport(buffer, selector);
        });
    // DOCUMENT screenshot
    } else if (selector === NOCLIP_SELECTOR || selector === DOCUMENT_SELECTOR) {
      chromy.screenshotMultipleSelectors(['body'], saveSelector);
    // OTHER-SELECTOR screenshot
    } else {
      chromy.screenshotMultipleSelectors(selectors, saveSelector);
    }

    chromy
      .end()
      .then(_ => {
        resolve();
      })
      .catch(e => {
        reject(e);
      });

    // result helpers

    // saveViewport: selectors will be `body` or `viewport` ONLY
    function saveViewport (buffer, selector) {
      const filePath = selectorMap[selector].filePath;

      ensureDirectoryPath(filePath);
      return fs.writeFile(filePath, buffer);
    }

    // saveSelector: selectorArr will contain any valid selector (not body or viewport).
    // If body *is* found in selector arr then it was originally DOCUMENT_SELECTOR -- and it will be reset back to DOCUMENT_SELECTOR -- this is because chromy takes a Document shot when BODY is used.
    function saveSelector (err, buffer, index, selectorArr) {
      let selector = selectorArr[index];
      if (selector === BODY_SELECTOR) {
        selector = DOCUMENT_SELECTOR;
      }
      const selectorProps = selectorMap[selector];
      const filePath = selectorProps.filePath;
      if (!selectorProps.exists) {
        return fs.copy(config.env.backstop + SELECTOR_NOT_FOUND_PATH, filePath);
      } else if (!selectorProps.isVisible) {
        return fs.copy(config.env.backstop + HIDDEN_SELECTOR_PATH, filePath);
      } else {
        if (err) {
          console.log('ChromyJS returned an unexpected error while attempting to capture a selector.', err);
          return new Error(err);
        }
        ensureDirectoryPath(filePath);
        return fs.writeFile(filePath, buffer);
      }
    }
  });
}
101503
function handleTernGetFile(request) {

            function replyWith(name, txt) {
                _postMessageByPass({
                    type: MessageIds.TERN_GET_FILE_MSG,
                    file: name,
                    text: txt
                });
            }

            var name = request.file;

            /**
             * Helper function to get the text of a given document and send it to tern.
             * If DocumentManager successfully gets the file's text then we'll send it to the tern node domain.
             * The Promise for getDocumentText() is returned so that custom fail functions can be used.
             *
             * @param {string} filePath - the path of the file to get the text of
             * @return {jQuery.Promise} - the Promise returned from DocumentMangaer.getDocumentText()
             */
            function getDocText(filePath) {
                if (!FileSystem.isAbsolutePath(filePath) || // don't handle URLs
                        filePath.slice(0, 2) === "//") { // don't handle protocol-relative URLs like //example.com/main.js (see #10566)
                    return (new $.Deferred()).reject().promise();
                }

                var file = FileSystem.getFileForPath(filePath),
                    promise = DocumentManager.getDocumentText(file);

                promise.done(function (docText) {
                    resolvedFiles[name] = filePath;
                    numResolvedFiles++;
                    replyWith(name, filterText(docText));
                });
                return promise;
            }

            /**
             * Helper function to find any files in the project that end with the
             * name we are looking for.  This is so we can find requirejs modules
             * when the baseUrl is unknown, or when the project root is not the same
             * as the script root (e.g. if you open the 'brackets' dir instead of 'brackets/src' dir).
             */
            function findNameInProject() {
                // check for any files in project that end with the right path.
                var fileName = name.substring(name.lastIndexOf("/") + 1);

                function _fileFilter(entry) {
                    return entry.name === fileName;
                }

                ProjectManager.getAllFiles(_fileFilter).done(function (files) {
                    var file;
                    files = files.filter(function (file) {
                        var pos = file.fullPath.length - name.length;
                        return pos === file.fullPath.lastIndexOf(name);
                    });

                    if (files.length === 1) {
                        file = files[0];
                    }
                    if (file) {
                        getDocText(file.fullPath).fail(function () {
                            replyWith(name, "");
                        });
                    } else {
                        replyWith(name, "");
                    }
                });
            }

            if (!isFileExcludedInternal(name)) {
                getDocText(name).fail(function () {
                    getDocText(rootTernDir + name).fail(function () {
                        // check relative to project root
                        getDocText(projectRoot + name)
                            // last look for any files that end with the right path
                            // in the project
                            .fail(findNameInProject);
                    });
                });
            }
        }
470251
function saveComponent(req, cb) {
  req.pause(); // Wait for tempdir.

  temp.mkdir('bowerball-', function (err, dirPath) {
    if (err) { return cb(err); }

    var filePath   = dirPath + '/component.json',
        fileStream = fs.createWriteStream(filePath, {flags: 'w', mode: '0600'});

    fileStream.on('open', function (fd) {
      req.on('end', function () { return cb(null, dirPath, filePath); });
      req.pipe(fileStream);
      req.resume();
    });
  });
}
1361069
function() {
          return through.obj(function(file, encode, done){
            addBefore(file.path);
            this.push(file);
            done();
          });
        }
21640
function openNewFile() {
                var fileOpenPromise;

                if (FileViewController.getFileSelectionFocus() === FileViewController.PROJECT_MANAGER) {
                    // If selection is in the tree, leave workingset unchanged - even if orig file is in the list
                    fileOpenPromise = FileViewController
                        .openAndSelectDocument(path, FileViewController.PROJECT_MANAGER);
                } else {
                    // If selection is in workingset, replace orig item in place with the new file
                    var info = MainViewManager.findInAllWorkingSets(doc.file.fullPath).shift();

                    // Remove old file from workingset; no redraw yet since there's a pause before the new file is opened
                    MainViewManager._removeView(info.paneId, doc.file, true);

                    // Add new file to workingset, and ensure we now redraw (even if index hasn't changed)
                    fileOpenPromise = handleFileAddToWorkingSetAndOpen({fullPath: path, paneId: info.paneId, index: info.index, forceRedraw: true});
                }

                // always configure editor after file is opened
                fileOpenPromise.always(function () {
                    _configureEditorAndResolve();
                });
            }
261321
function saveAsIndexedFile(
  bundle: RamBundleInfo,
  options: OutputOptions,
  log: (...args: Array<string>) => void,
): Promise<mixed> {
  const {
    bundleOutput,
    bundleEncoding: encoding,
    sourcemapOutput,
    sourcemapSourcesRoot,
  } = options;

  log('start');
  const {startupModules, lazyModules, groups} = bundle;
  log('finish');

  const moduleGroups = createModuleGroups(groups, lazyModules);
  const startupCode = joinModules(startupModules);

  log('Writing unbundle output to:', bundleOutput);
  const writeUnbundle = writeBuffers(
    fs.createWriteStream(bundleOutput),
    buildTableAndContents(startupCode, lazyModules, moduleGroups, encoding),
  ).then(() => log('Done writing unbundle output'));

  if (sourcemapOutput) {
    const sourceMap = buildSourcemapWithMetadata({
      startupModules: startupModules.concat(),
      lazyModules: lazyModules.concat(),
      moduleGroups,
      fixWrapperOffset: true,
    });
    if (sourcemapSourcesRoot !== undefined) {
      relativizeSourceMapInline(sourceMap, sourcemapSourcesRoot);
    }

    const wroteSourceMap = writeSourceMap(
      sourcemapOutput,
      JSON.stringify(sourceMap),
      log,
    );

    return Promise.all([writeUnbundle, wroteSourceMap]);
  } else {
    return writeUnbundle;
  }
}
609719
function(url, outFile, cb, persist, headers) {
    this.file.save(
      outFile,
      request.get(
        {
          url : url,
          headers : headers
        }
      ),
      persist,
      cb
    );
  }
565533
function sendReload() {
  if (saveChecksum) {
    $.ajax({
      url: jsbin.getURL() + '/reload',
      data: {
        code: jsbin.state.code,
        revision: jsbin.state.revision,
        checksum: saveChecksum
      },
      type: 'post'
    });
  }
}
596526
function clientSave() {

    u.each(sources, function(source) {

      var dirtyFiles = u.filter(source.files, function(file) {
        if (file._dirty) {  // 1 means unsaved, 2 means saving
          file._dirty = 2;  // side effect of filter
          return true;
        }
        return false;
      });

      if (dirtyFiles.length) {

        var files = u.map(dirtyFiles, generator.serializeFile);

        debug('clientSave %s files, %s...', files.length, files[0].text.slice(0,200));

        // static save from browser directly to source
        if (opts.staticHost && source.staticSrc && source.src) {

          // NOTE: subtle difference in data compared to httpClient.put()
          source.src.put(files, function(err, savedFiles) {

            if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) {
              // notify user on save errors
              return notify('error saving files, please check your internet connection');
            }

            u.each(dirtyFiles, function(file) {

              // no collision detection support with static saves (for now)
              file._oldtext = file.text;

              // only mark as clean if unchanged while waiting for save
              if (file._dirty === 2) { delete file._dirty; }
            });

            return source.verbose && notify(u.size(savedFiles) + ' file(s) saved');
          });
        }

        // normal (non-static) save from browser to pub-server
        else {
          httpClient.put({ source:source.name, files:files }, function(err, savedFiles) {

            if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) {
              if (err) { log(err); }
              // notify user on save errors
              return notify('error saving files, please check your internet connection');
            }

            u.each(dirtyFiles, function(file, idx) {

              var savedFile = savedFiles[idx];

              if (typeof savedFile !== 'object') {
                // most likely a collision - must notify user
                return notify('error saving file: ' + savedFile);
              }

              // preserve for next update
              file._oldtext = savedFile.text;

              // only mark as clean if unchanged while waiting for save
              if (file._dirty === 2) { delete file._dirty; }

            });

            return source.verbose && notify(u.size(savedFiles) + ' file(s) saved');
          });
        }
      }
    });
  }
720383
function(){
        var deferred = Q.defer();

        fs.readFile( this.path, "utf-8", function( err, data ){
            if( err ){
                deferred.reject( err );
                return;
            }
            this.srcHTMLCode = data;
            deferred.resolve( this );
        }.bind( this ) );

        return deferred.promise;
    }
951005
function(err) {
        var file = fs.realpathSync(this.file);
        if (!err) {
            this.console.info('Compiled code saved to', file);
        } else {
            this.console.info('Saving code failed to', file);
        }
    }
819225
function Saver() {
    var _saver;

    // Properties
    this.defaultFilename = 'artoo_data';
    this.defaultEncoding = 'utf-8';
    this.xmlns = 'http://www.w3.org/1999/xhtml';
    this.mimeShortcuts = {
      csv: 'text/csv',
      tsv: 'text/tab-separated-values',
      json: 'application/json',
      txt: 'text/plain',
      html: 'text/html',
      yaml: 'text/yaml'
    };

    // Methods
    this.createBlob = function(data, mime, encoding) {
      mime = this.mimeShortcuts[mime] || mime || this.defaultMime;
      return new Blob(
        [data],
        {type: mime + ';charset=' + encoding || this.defaultEncoding}
      );
    };

    this.createBlobFromDataURL = function(url) {
      var byteString = atob(url.split(',')[1]),
          ba = new Uint8Array(byteString.length),
          i,
          l;

      for (i = 0, l = byteString.length; i < l; i++)
        ba[i] = byteString.charCodeAt(i);

      return new Blob([ba.buffer], {
        type: url.split(',')[0].split(':')[1].split(';')[0]
      });
    };

    this.blobURL = function(blob) {
      var oURL = URL.createObjectURL(blob);
      return oURL;
    };

    this.saveResource = function(href, params) {
      var a = document.createElementNS(this.xmlns, 'a');
      a.href = href;

      a.setAttribute('download', params.filename || '');

      // Firefox needs the link attached to the page's DOM
      if ('document' in _root)
        document.body.appendChild(a);

      a.click();

      if ('document' in _root)
        document.body.removeChild(a);
      a = null;

      // Revoking the object URL if we want to
      if (params.revoke)
        setTimeout(function() {
          URL.revokeObjectURL(href);
        });
    };

    // Main interface
    this.saveData = function(data, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlob(data, params.mime, params.encoding);

      // Saving the blob
      this.saveResource(
        this.blobURL(blob),
        {
          filename: params.filename || this.defaultFilename,
          revoke: params.revoke || true
        }
      );
    };

    this.saveDataURL = function(url, params) {
      params = params || {};

      // Creating the blob
      var blob = this.createBlobFromDataURL(url);

      // Saving the blob
      this.saveResource(
        blob,
        {filename: params.filename || this.defaultFilename}
      );
    };
  }
1032855
function sendFile (req, res, next, file) {
  if (file instanceof Buffer) {
    setContentType(req, res, ["application/octet-stream", "*/*"]);

    // `file` is the file's contents
    util.debug("Sending raw buffer data");
    res.send(file);
    return;
  }

  if (typeof file === "string" || file instanceof String) {
    setContentType(req, res, ["application/octet-stream", "*/*"]);

    // `file` is the file's contents as as string
    util.debug("Sending raw string data");
    res.send(file);
    return;
  }

  // `file` is a file info object
  fs.exists(file.path || "", (exists) => {
    if (exists) {
      let isAttachment = _.some(res.swagger.headers, (header, name) => {
        return name.toLowerCase() === "content-disposition";
      });

      if (isAttachment) {
        // Get the filename from the "Content-Disposition" header,
        // or fallback to the request path
        let fileName = /filename\=\"(.+)\"/.exec(res.get("content-disposition"));
        fileName = fileName ? fileName[1] : req.path;

        util.debug('Sending "%s" as an attachment named "%s"', file.path, fileName);
        res.download(file.path, fileName);
      }
      else {
        util.debug('Sending "%s" contents', file.path);
        res.sendFile(file.path, { lastModified: false });
      }
    }
    else {
      // Throw an HTTP 410 (Gone)
      util.debug('Unable to find the file: "%s".  Sending an HTTP 410 (Gone)', file.path);
      next(ono({ status: 410 }, "%s no longer exists", file.path || req.path));
    }
  });
}
63329
function write(filepath, contents) {
  return new Promise((resolve, reject)=>{
    fs.writeFile(filepath, contents, (err, response)=>{
      if (err) return reject(err);
      return resolve(response);
    })
  });
}