How to create file on SFTP server in Cypress test - javascript

When I call the createFile() function in my Cypress test, I am trying to create a file on a hosted SFTP server.
Currently, when I call it, I get the following error message:
The following error was thrown by a plugin. We stopped running your tests because a plugin crashed. Please check your plugins file (C:\Dev\SFTP_POC\cypress\plugins\index.js)
Error: put: Internal server error.
sftp://myHost.com#sftp.next.rec-test.com:2022/reports/
at fmtError (C:\Dev\SFTP_POC\node_modules\ssh2-sftp-client\src\utils.js:55:18)
at WriteStream. (C:\Dev\SFTP_POC\node_modules\ssh2-sftp-client\src\index.js:728:18)
at Object.onceWrapper (events.js:418:26)
at WriteStream.emit (events.js:323:22)
at Object.cb (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:3629:12)
at 101 (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:2622:11)
at SFTP.push (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:278:11)
at CHANNEL_DATA (C:\Dev\SFTP_POC\node_modules\ssh2\lib\client.js:525:23)
at 94 (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\handlers.misc.js:859:16)
at Protocol.onPayload (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:2025:10)
at AESGCMDecipherNative.decrypt (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\crypto.js:987:26)
at Protocol.parsePacket [as _parse] (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:1994:25)
at Protocol.parse (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:293:16)
at Socket. (C:\Dev\SFTP_POC\node_modules\ssh2\lib\client.js:713:21)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Below is my current index.js code:
module.exports = (on, config) => {
on('task', {
createFile() {
const fs = require('fs');
let data = fs.createReadStream('C:/Dev/SFTP_POC/cypress/fixtures/example.json');
let remote = 'sftp://myHost.com:2022/reports/';
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const config = {
host: 'myHost.com',
port: '2022',
username: 'myUsername',
password: 'myPassword'
};
sftp.connect(config).then(() => {
sftp.put(data, remote);
})
.then(data => {
console.log('Success');
})
.then(() => {
sftp.end();
})
.catch(err => {
console.log(err);
})
return null;
}
})
}
My remote variable is a folder that exists on the server.
However, after the test, a new file isn't being added.
Can someone please tell me what I'm doing wrong here, & how to resolve it

Related

Error: read ECONNRESET when executing the javascript file

I want to access the Untis-API by using the npm package untis-api.
When I run the javascript file I get this error:
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error: read ECONNRESET
at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
My Code:
const w = require("untis-api");
const e = w.entities;
w.connect("USERNAME", "PASSWORD", "SCHOOL", "URL").then(() => {
w.getTeachers().then(teachers => {
console.log(teachers);
}).catch(err => {
console.log(err);
});
w.logOut();
}).catch(err => {
console.log(err);
});
How can I fix this?
I'm using Node Version 16.15.0
It was an error at the webuntis server. Due to a DDoS Attack, the service was temporarily unavailable. This causes the error.

npm-mysql crashes overnight

The class:
const mysql = require('mysql');
module.exports = function () {
this.connection = mysql.createConnection({
host : 'localhost',
user : 'USER',
password : 'PASSWORD',
database : 'DATABASE',
multipleStatements: true
});
this.query = (sql, args) => {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
});
});
};
this.close = () => {
return async () => {
try {
this.connection.end(err => {
if (err) throw err;
return;
});
} catch(e) {
return e;
}
}
};
};
In index i call it like this:
const Database = require('./server/modules/mysql'),
connection = new Database();
The problem:
Overnight mysql crashes:
[nodemon] starting `node index.js`
listening on port 420
events.js:292
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
[nodemon] app crashed - waiting for file changes before starting...
I'm using Nodemon and a simple restart to the application solves the issue until the next morning (or next long period of not coding.)
I'm not really using close() anywhere or after anything since in the docs it says it's not needed, just query().
but clearly i get a timeout somewhere somehow, like i should deal with the opening and closing of connection.
Do i need to close connections after making queries in my app?
Is there a way to set the timeout limit or dealing with him?
Am i just setting it up wrong or using wrong/outdated tool?
Thanks.

can't set host to node net.socket connect

I'm using electron-vue build an APP. I need create a tcp connection, and I use net.Socket().But i get a no response when I set HOST.
I need use the socket global, so I create a class like this:
import crc16ccitt from 'crc/crc16ccitt';
const net = require('net');
class TcpClient {
tcp = null;
alive = false;
connect(options) {
return new Promise((resolve, reject) => {
this.tcp = new net.Socket();
this.tcp.connect(options, () => {
this.alive = true;
resolve();
console.log('connect server');
});
this.tcp.on('close', () => {
this.alive = false;
console.log('close');
reject();
});
this.tcp.on('error', () => {
console.log('error');
});
});
}
}
export default TcpClient;
and then I put it in the main.js like this:
Vue.prototype.$tcp = new TcpClient();
but when I use in vue instance like this:
this.$tcp.connect({ port: 8000, host: 127.0.0.1 });
Nothing happend, no errors, no result, but when I reload my page, I think connect a moment, and my server shows:
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
And if I don't set HOST, just port, it works well.

How to copy files between pods or execute in a pod?

I'm trying to execute a terminal command in a pod to get the file content.
It works fine on local:
const Client = require('kubernetes-client').Client;
const Config = require('kubernetes-client/backends/request').config;
const Request = require('kubernetes-client/backends/request');
const config = Config.fromKubeconfig();
const client = new Client({ config: config, version: '1.13' });
const podResponse = await client.api.v1.namespaces(config.namespace).pods(<pod name>).exec.get({
qs: {
command: ['cat', 'README.md'],
container: <container name>,
stdout: true,
stderr: true,
},
});
console.log(podResponse.body);
When I run my Node.js app on Cluster with following changes:
const config = Request.config.getInCluster();
const backend = new Request(config);
const client = new Client({ backend });
it still works fine. I can get pods/services info (Node.js app run on same cluster/namespace)..
But .exec.get doesn't work. It fails with:
{ Error: Unexpected server response: 401
at ClientRequest.req.on (/usr/local/app/node_modules/ws/lib/websocket.js:579:7)
at ClientRequest.emit (events.js:182:13)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
at TLSSocket.socketOnData (_http_client.js:442:20)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:94:17) messages: [] }
Again, I don't need to pass any auth info.. It works fine to get pods/services details.
Seems the issue will be fixed in new release:
kubernetes-client repo
So wondering if there is other way to copy a file from a pod by JavaScript, i.e. analog of:
kubectl cp <file-spec-src> <file-spec-dest>
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
//Copy File from Local folder to POD
const namespaceName = "default";
const podName = "logging-poc-standalone-app-694db6684c-6dsw4";
const containerName = "logging-poc-standalone-app";
const cp = new k8s.Cp(kc);
cp.cpToPod(namespaceName, podName, containerName, "log.log", "/var/log").catch(
(err) => {
console.log(err);
}
);

How to fix MaxListenersExceededWarning error?

In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}

Categories

Resources