How can I catch an upload error in node js via ftp? For example when my computer loses the connection. I am using ftp module and nothing of this(error, close or end) throws any errors. Or may be there are any other solutions, i mean another npm module?
var Client = require('ftp');
var c = new Client();
c.on('ready', callback);
c.on('error', function(err){
console.log(err);
});
c.on('close', function(err){
console.log(err);
});
c.on('end', function(){
console.log("END");
});
c.connect({
host: host,
port: port,
user: username,
password: password
});
...
c.put(uploadfile, uploadpath, onupload);
I know that this is not the best idea to edit the library, but i solved my problem by adding this code
if(err.indexOf("ECONNRESET") > -1){
this._reset();
}
after
sock.once('error', function(err) {
self.emit('error', err);
on 965 line in connection.js of ftp library.
Related
today I've got a problem with jsftp.
When I'm running my script and upload.txt is empty,
jsftp is correctly uploading an empty file to the server.
When upload.txt is a utf-8 javascript file for example const x = "Hello World!";,
jsftp is uploading a file named .pureftpd-upload.5e35d750.15.79c5.1b3bbd87 with 0 bytes (= no data).
Here's my script:
var ftp = new jsftp({
host: "ftp.example.url",
port: 21,
user: user.name,
pass: user.pass
});
ftp.auth(user.name, user.pass, function(err){
if(err){
openDialog();
console.error(err);
throw err;
}
else{
ftp.put(path_datafile, '/directory/hello.js', function(err){
console.error(err);
throw err;
});
}
});
(There are no errors in the output)
For the people saying you need to read the file first:
var ftp = new jsftp({
host: "ftp.example.url",
port: 21,
user: user.name,
pass: user.pass
});
fs.readFile(path_datafile, 'utf8', function(err, buff){
if(err){
console.log(err);
}
else{
ftp.put(buff, '/directory/hello.js', function(err){
console.error(err);
throw err;
});
}
});
Didn't worked at all.
Then it is showing the error:
Local file doesn't exist
The error here is that the fs module is now converting the file
to utf-8 fs.readfile(file, 'utf8', action).
To solve that problem, only write fs.readfile(file, action),
so that the file is outputted in bytes.
The script will output false but work fine.
So Ragnar is right.
His answer is correct, when you aren't using utf8 encoding with fs.
Don't use it and it will work.
Ragnar:
https://stackoverflow.com/users/1052928/ragnar
His Answer:
https://stackoverflow.com/a/26939160/12470434
This is my first ever question on here so please excuse any abnormalities in etiquette.
I am new to Node.js and backend programming in general.
Right now I am using Node and Tedious to connect to a local SQL server. I'd like to keep my main.js file clean and so am trying to put everything related to my SQL connection in a separate js file. Below would be the simplest possible form I have for my main.js.
var http = require('http');
var sqlmodule = require('./SQLconnection');
http.createServer(function (req, res) {
sqlmodule.makeConnection();
}).listen(8080);
I then have my SQLconnection.js file.
var Connection = require('tedious').Connection;
exports.makeConnection = function () {
var config = {
userName: 'XXXXXX',
password: 'XXXXXX',
server: 'XXXXXX'
};
var connection = new Connection(config);
};
//The below code is my event listener but I don't know how
//to incorporate it as part of the module.
connection.on('connect', function(err) {
if (err) {
console.error('Connection error', err);
} else {
console.log('Connected');
}
});
I have no problems when the listener isn't present in the file, but I can't find a way to have it part of the SQLconnection.js module. I've tried adding exports and module.exports before it in a few ways but to no success. It listening for an event and not being a normal function is stumping me.
How would I go about getting the event listeners in the separate file?
I'm also trying to go about this as vanilla as possible, so I'm just using Node.js and Tedious at this point.
change
exports.makeConnection = function () {
to
function makeConnection() {
...
module.exports = {makeConnection}
As an additional change, you need to put your connection listener in the sames scope as the connection variable. Personally, I would also have makeConnection return a Promise with the connection so you are not operating on a connection that has failed/not yet connected. Something like
var Connection = require('tedious').Connection;
function makeConnection() {
var config = {
userName: 'XXXXXX',
password: 'XXXXXX',
server: 'XXXXXX'
};
return new Promise((resolve, reject) => {
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) return reject(err);
resolve(connection);
});
}
};
module.exports = {makeConnection}
I need to be able to run '/etc/init.d/mongod status' or 'service mongod status' from wihtin a node js file, in order to store the response in the database.
When I run the above commands in the command line, I get the following response:
● mongod.service - SYSV: Mongo is a scalable, document-oriented database.
Loaded: loaded (/etc/rc.d/init.d/mongod)
Active: active (running) since Thu 2017-02-02 08:07:42 UTC; 3h 27min ago
Docs: man:systemd-sysv-generator(8)
Process: 793 ExecStart=/etc/rc.d/init.d/mongod start (code=exited, status=0/SUCCESS)
Main PID: 1027 (mongod)
CGroup: /system.slice/mongod.service
└─1027 /usr/bin/mongod -f /etc/mongod.conf
However, I want to include this status in an API response that I write. Therefore, when a user request my API, I want it to return the mongoDB status check as seen above.
I have tried the following ways:
router.get('/status', function(req, res) {
var databaseCheck = service mongod status // not sure how to do this
res.json({
mongoResponse: '//to have the above status check response here'
});
});
I am new to all this, so any help would be appreciated. I may understand that my thinking is wrong - do let me know if there is a different way of doing this please
Connect a database and then check connection like db.serverConfig.isConnected(). The below code is a full example.
const app = express();
let dbClient;
let db;
let collection;
MongoClient.connect(configuration.mongoDbUri, { useNewUrlParser: true, poolSize: 30 }, (error, client) => {
if (error) {
console.log("Connection failed for some reason. Err: ", error);
return error;
}
db = client.db("myDB");
dbClient = client;
collection = db.collection('myCollection');
app.locals.mongoDb = db;
});
app.get("/status", (req, res) => {
if (db.serverConfig.isConnected()) {
console.log("db.serverConfig.isConnected :", db.serverConfig.isConnected());
return res.send({ result: true});
}
return res.send({ result: false});
});
app.listen(configuration.app.port, error => {});
You can use nodejs child-process module to run a shell command like you would from a terminal. In a terminal you would "service mongod status", in the nodejs child-process you would do the same by putting that command as an argument to the child-process execute function, like so:
const exec = require('child_process').exec;
exec('service mongod status', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
Try code like this into you app:
db.serverConfig.isConnected();
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});
I'm looking for a way to check which files are present in a remote directory i want to access via ssh or similar and write the filenames into an array.
So far I had no luck. unix rsync has an -n flag which can print every file which is present at the destinated location, but I don't get how to use the rsync-output in grunt.
Here's how you might do it via sftp with ssh2:
var SSH2 = require('ssh2');
var conn = new SSH2();
conn.on('ready', function() {
conn.sftp(function(err, sftp) {
if (err) throw err;
sftp.readdir('/tmp', function(err, list) {
if (err) throw err;
console.dir(list);
conn.end();
});
});
}).connect({
host: '192.168.100.100',
port: 22,
username: 'frylock',
// password: 'foobarbaz',
privateKey: require('fs').readFileSync('/here/is/my/key')
});