MCPcopy Create free account
hub / github.com/mscdex/ssh2 / writeFile

Method writeFile

lib/protocol/SFTP.js:639–697  ·  view source on GitHub ↗
(path, data, options, callback_)

Source from the content-addressed store, hash-verified

637 });
638 }
639 writeFile(path, data, options, callback_) {
640 if (this.server)
641 throw new Error('Client-only method called in server mode');
642
643 let callback;
644 if (typeof callback_ === 'function') {
645 callback = callback_;
646 } else if (typeof options === 'function') {
647 callback = options;
648 options = undefined;
649 }
650
651 if (typeof options === 'string')
652 options = { encoding: options, mode: 0o666, flag: 'w' };
653 else if (!options)
654 options = { encoding: 'utf8', mode: 0o666, flag: 'w' };
655 else if (typeof options !== 'object')
656 throw new TypeError('Bad arguments');
657
658 if (options.encoding && !Buffer.isEncoding(options.encoding))
659 throw new Error(`Unknown encoding: ${options.encoding}`);
660
661 const flag = options.flag || 'w';
662 this.open(path, flag, options.mode, (openErr, handle) => {
663 if (openErr) {
664 callback && callback(openErr);
665 } else {
666 const buffer = (Buffer.isBuffer(data)
667 ? data
668 : Buffer.from('' + data, options.encoding || 'utf8'));
669 const position = (/a/.test(flag) ? null : 0);
670
671 // SFTPv3 does not support the notion of 'current position'
672 // (null position), so we just attempt to append to the end of the file
673 // instead
674 if (position === null) {
675 const tryStat = (er, st) => {
676 if (er) {
677 // Try stat() for sftp servers that may not support fstat() for
678 // whatever reason
679 this.stat(path, (er_, st_) => {
680 if (er_) {
681 return this.close(handle, () => {
682 callback && callback(er);
683 });
684 }
685 tryStat(null, st_);
686 });
687 return;
688 }
689 writeAll(this, handle, buffer, 0, buffer.length, st.size, callback);
690 };
691 this.fstat(handle, tryStat);
692 return;
693 }
694 writeAll(this, handle, buffer, 0, buffer.length, position, callback);
695 }
696 });

Callers 1

appendFileMethod · 0.95

Calls 4

openMethod · 0.95
fstatMethod · 0.95
callbackFunction · 0.85
writeAllFunction · 0.85

Tested by

no test coverage detected