how to return the values (data) of the getData function bellow?
const { Client } = require('ssh2');
const conn = new Client();
function getData() {
//i tried to assign the data to a variable but failed
//var rawData = '';
conn.on('ready', () => {
conn.exec('pwd', (err,stream)=>{
if (err) throw err;
stream.on('data',(data)=>{
//the console successfully displayed - the current path
console.log('Output:' + data);
//if i return the data here the output was undefined
//return data
});
stream.stderr.on('data',(data)=>{
});
stream.on('close',(code,signal)=>{
conn.end();
});
//if i tried to get the data values here, it threw "unhandled 'error' event", so i would not possible to return the data here.
//console.log(data);
});
}).connect({
host: 'myserver',
port: 22,
username: 'root',
password: 'roots!'
});
}
getData();
consoling out from inside stream is success, but how to return the data?
i tried to assign the data to variable (rawaData), but confusing where to put the 'return' code.
You can use a promise to communicate back the final result:
function getData() {
return new Promise((resolve, reject) => {
let allData = "";
conn.on('ready', () => {
conn.exec('pwd', (err, stream) => {
if (err) {
reject(err);
conn.end();
return;
}
stream.on('data', (data) => {
allData += data;
});
stream.on('close', (code, signal) => {
resolve(allData);
conn.end();
});
stream.on('error', reject);
});
}).connect({
host: 'myserver',
port: 22,
username: 'root',
password: 'roots!'
});
});
}
getData().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});;
I am trying to read data in stream from a remote server log file, which is continuously growing. I want to display the new lines added to my local console. I am using ssh for connection from local to remote server.
I found below solution on github which is writing local file content to remote file but i want in other way. Not getting an idea to convert this in reverse direction.
var Connection = require('ssh2');
var fs = require('fs');
var BufferedStream = require('buffered-stream');
console.log('sshstream started')
connectSSH();
function readFile(filepath, startOffset, outputStream) {
var fileSize = fs.statSync(filepath).size;
var length = fileSize - startOffset;
var myFD = fs.openSync(filepath, 'r');
var readable = fs.createReadStream(filepath, {
fd: myFD, start: startOffset, end: fileSize, autoClose: true
})
return readable;
}
function connectSSH(){
var c = new Connection();
c.on('connect', function() {
console.log('Connection :: connect');
});
c.on('ready', function() {
console.log('Connection :: ready');
c.shell('', function(err, stream) {
if (err) throw err;
stream.on('data', function(data, extended) {
console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
+ data);
});
stream.on('end', function(code, signal) {
console.log('Stream :: EOF', code, signal);
});
stream.on('close', function(code, signal) {
console.log('Stream :: close', code, signal);
});
stream.on('exit', function(code, signal) {
console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
c.end();
});
stream.on('drain', function() {
console.log('Stream :: drain');
});
var bufferStream = new BufferedStream(4*1024*1024);
bufferStream.pipe(stream);
stream.write('cat - >> /home/username/mylog.log');
readable = readFile('test.log', 0, bufferStream);
readable.once('end', function(){
console.log("ENDED");
});
readable.pipe(bufferStream).pipe(stream);
});
});
c.on('error', function(err) {
console.log('Connection :: error :: ' + err);
});
c.on('end', function() {
console.log('Connection :: end');
});
c.on('close', function(had_error) {
console.log('Connection :: close');
});
c.connect({
host: 'xx.xxx.xx.xxx',
port: 22,
username: 'username',
password: 'password'
});
}
Please suggest
Thanks
This works and it could be customized as you wish.
'use strict';
const SSH = require('simple-ssh');
function run(sshConfig, script) {
return new Promise((resolve, reject) => {
let scriptOutput = '';
const sshFtw = new SSH(sshConfig);
sshFtw.exec(script,
{ out: console.log.bind(console) })
.on('error', (err) => reject(err))
.on('close', () => resolve(scriptOutput))
.start();
});
};
run({
"host": "1.2.3.4",
"user": "my-user",
"pass": "my-psw"
}, 'tail -f /home/my-app/log/api-out.log');
I'm trying to get the data from LDAP and I'm getting it successfully but it's not written into variable so then after the code is executed I can make some checks on the data.
var server = LdapJS.createClient({
url: LdapConf.server.url,
tlsOptions: LdapConf.server.tlsOptions
});
server.bind(LdapConf.server.bindDN, LdapConf.server.bindCredentials, function(err) {
if (err) {
return done(err);
}
});
var SearchOtps = {
filter: '(uid=' + username + ')',
scope: 'one',
};
var UserSearch = server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
res.on('searchEntry', function(entry) {
console.log('entry: ' + JSON.stringify(entry.object));
return (JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
//console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
//console.error('error: ' + err.message);
});
res.on('end', function(result) {
//console.log('status: ' + result.status);
});
});
console.log(UserSearch);
I just do not know how to stop further code execution while it's waiting for the return of the LDAP search.
Server Started
undefined
You could do a function that returns it in promise.
function UserSearch(server,LdapConf, SearchOtps) {
return new Promise(function(resolve,reject) {
server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
res.on('searchEntry', function(entry) {
console.log('entry: ' + JSON.stringify(entry.object));
resolve(JSON.stringify(entry.object)));
});
res.on('searchReference', function(referral) {
//console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
reject()
});
res.on('end', function(result) {
//console.log('status: ' + result.status);
});
});
}
}
UserSearch(server,LdapConf, SearchOtps)
.then(function(res) {
console.log(res)
})
i have some callbacks inside my promise:
var res = new Promise(resolve => {
console.log('trig1');
var out = fs.createWriteStream(pathToFile);
console.log('trig2');
out.on('finish', function() {
console.log('out finish')
})
out.on('close', function() {
console.log('out close')
})
out.on('error', function(err) {
console.log('out error: ' + err)
})
})
When i call this promise, it creates the file on the path and prints:
trig1
trig2
Nothing more. Why are my callbacks not executed?
Greetings and thanks
Because there was no error, you didn't write anything, and you didn't close this stream. That's why any of those events fired.
Try to change your code so it will do something.
var res = new Promise(resolve => {
console.log('trig1');
var out = fs.createWriteStream(pathToFile);
console.log('trig2');
out.on('finish', function() {
console.log('out finish')
})
out.on('close', function() {
console.log('out close')
})
out.on('error', function(err) {
console.log('out error: ' + err)
});
out.close(); // this will fire `close` event
})
I'm using Imap with node.js, and every time i connect it, it fetch al the emails from a data i gave it, but doens't mark them as read, so the following time it re-fecth them again.
Here is my code(All the functions implemented here are called in a main.js file), what can I change to mark the e-mail I'm fetching as read?
I've tried to do like written here (how to mark unseen email as seen with node-imap in node.js) but it didn't work..
var Imap = require('imap');
var inspect = require('util').inspect;
var formatter = require('./formatter.js');
var mailError = exports.mailError = [];
var imap = new Imap({
user: 'aaaaaaaaa#gmail.com',
password: 'xxxxxxx',
host: 'imap.gmail.com',
port: 993, //Perchè non 143, standard IMAP?
tls: true,
markSeen: true
});
function openInbox(cb) {
imap.openBox('INBOX', false, cb);
}
var onBodyCb = exports.onBodyCb = function(parsedHeaders, body){
var pos = (body.indexOf("Delivery to the following recipient failed permanently:") + 55);
var address = body.substr(pos,50);
var at = address.indexOf("#");
address = address.substr(0,at+formatter.company.length+formatter.domain.length+2);
address = address.replace(/ /g,'');
address = address.replace(/(\r\n|\n|\r)/gm,"");
console.log("onBodyCB: "+address+'\n');
mailError.push(address);
};
var onFinishedFetching = exports.onFinishedFetching = function(){};
imap.once('ready', function() {
var fs = require('fs'), fileStream;
openInbox(function(err, box) {
if (err) throw err;
imap.search([ 'UNSEEN', ['SINCE', 'July 10, 2014'] ], function(err, results) {
if (err) throw err;
// a questo abbiamo la box a cui possiamo accedere
var f = imap.fetch(results, { bodies: '' });
f.on('message', function(msg, seqno) {
//console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
console.log(prefix + 'Body');
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
//console.log(buffer);
stream.once('end', function() {
//console.log(prefix + 'Parsed header: %s', inspect());
var header = Imap.parseHeader(buffer);
exports.onBodyCb(header, buffer);
});
});
//msg.once('attributes', function(attrs) {
// console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
//});
msg.once('end', function() {
//console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
exports.onFinishedFetching();
});
});
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
exports.connect = function(){
imap.connect();
};
EDIT:
I've changed as suggested but it still doesn't work...
var Imap = require('imap');
var inspect = require('util').inspect;
var formatter = require('./formatter.js');
var mailError = exports.mailError = [];
var imap = new Imap({
user: 'marco.loco.recruiter#gmail.com',
password: 'coci2014',
host: 'imap.gmail.com',
port: 993, //Perchè non 143, standard IMAP?
tls: true,
markSeen : true,
markRead : true
});
function openInbox(cb) {
imap.openBox('INBOX', false, cb);
}
var onBodyCb = exports.onBodyCb = function(parsedHeaders, body){
var pos = (body.indexOf("Delivery to the following recipient failed permanently:") + 55);
var address = body.substr(pos,50);
var at = address.indexOf("#");
address = address.substr(0,at+formatter.company.length+formatter.domain.length+2);
address = address.replace(/ /g,'');
address = address.replace(/(\r\n|\n|\r)/gm,"");
console.log("onBodyCB: "+address+'\n');
mailError.push(address);
};
var onFinishedFetching = exports.onFinishedFetching = function(){};
imap.once('ready', function() {
var fs = require('fs'), fileStream;
openInbox(function(err, box) {
if (err) throw err;
imap.search([ 'UNSEEN', ['SINCE', 'July 10, 2014'] ], function(err, results) {
if (err) throw err;
// a questo abbiamo la box a cui possiamo accedere
var f = imap.fetch(results, { bodies: '' });
f.on('message', function(msg, seqno) {
//console.log('Message #%d', seqno);
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
//console.log(prefix + 'Body');
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
//console.log(buffer);
stream.once('end', function() {
//console.log(prefix + 'Parsed header: %s', inspect());
var header = Imap.parseHeader(buffer);
exports.onBodyCb(header, buffer);
});
});
//msg.once('attributes', function(attrs) {
// console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
//});
msg.once('end', function() {
//console.log(prefix + 'Finished');
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
exports.onFinishedFetching();
});
});
},false);
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
exports.connect = function(){
imap.connect();
};
var Imap = require("imap");
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
Promise.longStackTraces();
var imapConfig = {
user: 'USERNAME',
password: 'PASSWORD',
host: 'HOST',
port: 993,
tls: true
};
var imap = new Imap(imapConfig);
Promise.promisifyAll(imap);
imap.once("ready", execute);
imap.once("error", function(err) {
log.error("Connection error: " + err.stack);
});
imap.connect();
function execute() {
imap.openBox("INBOX", false, function(err, mailBox) {
if (err) {
console.error(err);
return;
}
imap.search(["UNSEEN"], function(err, results) {
if(!results || results.length){console.log("No unseen email available"); imap.end();return;}
imap.setFlags(results, ['\\Seen'], function(err) {
if (!err) {
console.log("marked as read");
} else {
console.log(JSON.stringify(err, null, 2));
}
});
var f = imap.fetch(results, { bodies: "" });
f.on("message", processMessage);
f.once("error", function(err) {
return Promise.reject(err);
});
f.once("end", function() {
console.log("Done fetching all unseen messages.");
imap.end();
});
});
});
}
function processMessage(msg, seqno) {
console.log("Processing msg #" + seqno);
// console.log(msg);
var parser = new MailParser();
parser.on("headers", function(headers) {
console.log("Header: " + JSON.stringify(headers));
});
parser.on('data', data => {
if (data.type === 'text') {
console.log(seqno);
console.log(data.text); /* data.html*/
}
// if (data.type === 'attachment') {
// console.log(data.filename);
// data.content.pipe(process.stdout);
// // data.content.on('end', () => data.release());
// }
});
msg.on("body", function(stream) {
stream.on("data", function(chunk) {
parser.write(chunk.toString("utf8"));
});
});
msg.once("end", function() {
// console.log("Finished msg #" + seqno);
parser.end();
});
}
{markRead: true} flag sometime it doesn't work, so you need to call set imap.setFlags([uuids], ['\Seen'], cb) explicitly
This is old question, but I had the same problem today. in the imap.seq.fetch call, there needs to be markSeen:true besides the bodies:"" . it should look like fetch(results,{bodies:"", markSeen:true}) –
And don't forget to open the Inbox in read-write mode as so many have said. imap.openBox('INBOX', false, cb)
Here is a working example to do the same.
var Imap = require('imap'),
inspect = require('util').inspect;
var imap = new Imap({
user: 'USERNAME',
password: 'PASSWORD',
host: 'IMAP_HOST',
port: 993, // Default port is 993
tls: true,
tlsOptions: {rejectUnauthorized: false}
});
function openInbox(cb) {
// openReadOnly = false
imap.openBox('Inbox', false, cb);
}
imap.once('ready', function () {
openInbox(function (err, box) {
if (err) throw err;
// Search emails having "Some Subject" in their Subject headers
imap.search([['HEADER', 'SUBJECT', 'Some Subject']], function (err, results) {
if (err) throw err;
try {
var f = imap.fetch(results, {bodies: 'TEXT'});
f.on('message', function (msg, seqno) {
msg.on('body', function (stream, info) {
var buffer = '';
stream.on('data', function (chunk) {
buffer += chunk.toString('utf8');
});
stream.once('end', function () {
// Mark the above mails as read
msg.once('attributes', function (attrs) {
let uid = attrs.uid;
imap.addFlags(uid, ['\\Seen'], function (err) {
if (err) {
console.log(err);
} else {
console.log("Marked as read!")
}
});
});
});
});
});
f.once('end', function () {
imap.end();
});
} catch (errorWhileFetching) {
console.log(errorWhileFetching.message);
imap.end();
}
});
});
});
imap.connect();