Nodejs Webdav read multiple files (Problem with Array) - node.js

I am starting using NodeJs and webdav, I am using websockets to receive a list with the names of the images that I need to send to my app and then I have a for loop to send them to my app, but for some reason some of the images are undefined.
I am starting using NodeJs and webdav so I have no idea what's wrong.
for(let i = 0; i < ImagemList.length; i++){
wfs.readFile(ImagemList[i], "binary", function(err, data) {
Imagens[i] = data;
if(Imagens.length == ImagemList.length){
socket.emit("ImagemPost", Imagens);
}
});
}
For some reason I can't acess the variable "i" and for some reason the data was going to a random place leaving empty spots.
I've updated the code and it still goes to random places (don't know why) but doesn't leave any empty spot.
My array is still random if someone can help me.
Imagem = Imagem.replace("[", "");
Imagem = Imagem.replace("]", "");
let ImagemList = Imagem.split(", ");
let Imagens = [];
let contador = 0;
for(let o = 0; o < ImagemList.length; o++){
wfs.readFile(ImagemList[o], "binary", function(err, data) {
Imagens[contador] = (data);
contador++;
if(Imagens.length == ImagemList.length){
socket.emit("ImagemPost", Imagens);
}
});
}

Related

is there a way to make my code non case sensitive

I'm trying to make a bot able to read an input automatically, no need for a command and then check the input against a list of defined words. I have managed to get this working but i'm having trouble in such a way that if anything varies from the word on the list, the bot ignores it. Code is as follows, all help is appreciated:
bot.on('message', message => {
for (i = 0; i < blacklist.length; i++)
{
//var check = blacklist[i].trim();
if (blacklist[i].trim().length > 0){
var lookup = '\\b'+blacklist[i]+'\\b';
var re = new RegExp(lookup);
var foundpos = message.content.search(re)
if(foundpos >=0) {
message.delete();
break;
}}}
for(i in blacklist) {
console.log(blacklist[i]);
}
})

looping through an array of objects using node js and mongodb

i am new with using mongodb and node am trying to loop through an array of objects from my database and display only the objects using a res.json, in my console.log it displays all the object, but in my postman using res.json it displays only one object please help
MY CODE
const course = res.GetUserDT.coursesHandled;
for (let index = 0; index < course.length; index++) {
console.log(course[index]);
}
const course = res.GetUserDT.coursesHandled;
for (let index = 0; index < course.length; index++) {
res.json(course[index]);
}
my console output
{ courseCode: '2103' }
{ courseCode: '2012' }
{ courseCode: '2062' }
my postman output
{ courseCode: '2103' }
Hi and welcome to Stackoverflow.
The Problem here is that res.json() sends a an immidiate response to the requestor - meaning a response is sent already within the first iteration of your for-loop.
I am also wondering why you need that loop - as you are not doing anything within it. So why don't you just send the array immidiately like so:
res.json(res.GetUserDT.coursesHandled);
You can only send res.json once.
To send all of them together you can create an array, push all the objects in the array and send it back as a response.
let arrayToReturn = []
for (let index = 0; index < course.length; index++) {
arrayToReturn.push(course[index])
}
res.json(arrayToReturn);
Update
#David's answer is the most accurate solution i.e just directly send the array as a response instead of looping
res.json(res.GetUserDT.coursesHandled);
Assuming that is express, res.json() will send the data and end the response.
try something like:
const responseArray = [];
for (let index = 0; index < course.length; index++) {
responseArray.push( course[index] );
}
res.json(responseArray);

Loop problems with Telegram bot

I'm currently developping a telegram bot.
Here's my code:
bot.command('check', ctx => {
console.log(ctx.from.id, ctx.chat.id)
var files = getFilesFromDir("toSend", [".txt"])
if(files.length > 0){
for (i = 0; i < files.length; i++) {
const url = 'https://api.telegram.org/bot'+bot_token+'/sendDocument'
let r = request(url, (err, res, body) => {
if(err) console.log(err)
console.log(body)
})
console.log(files[i])
let f = r.form()
f.append('chat_id', '476090013')
f.append('document', fs.createReadStream("tosend/"+files))
}
}else{
console.log('r')
}
})
My problems is the loop, I tried the for but I can't figured out.
I have a folder named tosend, I want that every file in there to be transfered to telegram api.
For one file it's working but if in the folder there are more than one file, f.append('document', fs.createReadStream("tosend/"+files)) the +files take every name instead of one.
You're trying to create a stream from an array of files: +files (which will return a comma separated string with all the filenames).
You need to use files[i] to create a stream per file.
f.append('document', fs.createReadStream("tosend/" + files[i]))

Using socketio-file-upload to upload multiple files

Im using NodeJS with socket.io and socketio-file-upload to upload multiple files, it works great! However I'm having an issue where I'm trying to save the name attribute of the input these files come to save them into my DB.
When I upload 1 or more files, I can't seem to access the input field name or something that shows me which of the files come from which input field.
Here is my front:
var uploader = new SocketIOFileUpload(socket);
var array_files_lvl_3 = [
document.getElementById("l3_id_front"),
document.getElementById("l3_id_back"),
document.getElementById("l3_address_proof_1"),
document.getElementById("l3_address_proof_2"),
document.getElementById("l3_passport")
];
uploader.listenOnArraySubmit(document.getElementById("save_level_3"), array_files_lvl_3);
And here is my back:
var uploader = new siofu();
uploader.dir = "uploads/userL3";
uploader.listen(socket);
uploader.on('saved', function(evnt){
console.log(evnt);
//this "event" variable has a lot of information
//but none of it tells me the input name where it came from.
});
This is what the "evnt" variable holds:
Unfortunately the library doesn't send that information. So there is nothing existing config you can do. So this needs code modification.
client.js:374
var _fileSelectCallback = function (event) {
var files = event.target.files || event.dataTransfer.files;
event.preventDefault();
var source = event.target;
_baseFileSelectCallback(files, source);
client.js:343
var _baseFileSelectCallback = function (files, source) {
if (files.length === 0) return;
// Ensure existence of meta property on each file
for (var i = 0; i < files.length; i++) {
if (source) {
if (!files[i].meta) files[i].meta = {
sourceElementId: source.id || "",
sourceElementName: source.name || ""
};
} else {
if (!files[i].meta) files[i].meta = {};
}
}
After these changes I am able to get the details in event.file.meta
I'm the author of socketio-file-upload.
It looks like the specific input field is not currently being recorded, but this would not be a hard feature to add. Someone opened a new issue and left a backpointer to this SO question.
A workaround would be to directly use submitFiles instead of listenOnArraySubmit. Something like this might work (untested):
// add a manual listener on your submit button
document.getElementById("save_level_3").addEventListener("click", () => {
let index = 0;
for (let element of array_files_lvl_3) {
let files = element.files;
for (let file of files) {
file.meta = { index };
}
uploader.submitFiles(files);
index++;
}
});

async in for loop in node.js without using async library helper classes [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I am a beginner to node.js. I was trying out the examples from the 'learnyounode' tutorial. I am trying to write a program that takes three url parameters and fetches some data from those urls and displays the returned data in the order in which the urls were provided.
var http = require('http');
var bl = require('bl');
var url = [];
url[0] = process.argv[2];
url[1] = process.argv[3];
url[2] = process.argv[4];
var data = [];
var remaining = url.length;
for(var i = 0; i < url.length; i++){
http.get(url[i], function (response){
response.setEncoding('utf8');
response.pipe(bl(function (err, chunk){
if(err){
console.log(err);
}
else{
data[i] = chunk.toString();
console.log(data[i]);
remaining -= 1;
if(remaining == 0) {
for(var j = 0; j < url.length; j++){
console.log(data[j]);
}
}
}
}));
});
}
I have two console.log statements in the program. The output i get is as follows:
It'll be chunder where lets throw a ford. We're going durry where mad as a cooee
.
Shazza got us some apples with come a strides. Mad as a swag when get a dog up y
a roo. It'll be rapt piece of piss as cunning as a trackie dacks.
As cross as a bogged with watch out for the boardies. As cunning as a digger fla
min lets get some roo bar. As dry as a piker piece of piss he hasn't got a joey.
Lets throw a strides mate we're going digger.
undefined
undefined
undefined
It seems like the data is correctly fetched and stored in the 'data' array but it still displays undefined.
Any idea why this is happening?
Thanks in advance!
This is a very common issue in async programming in node.js or even in the browser. A main issue you have is that the loop variable i will not be what you want it to be some time later when the async callback is called. By then, the for loop will have run to the end of its loop and i will be at the end value for all response callbacks.
There are numerous ways to solve this. You can use a closure to close over the i value and make it uniquely available to each callback.
var http = require('http');
var bl = require('bl');
var url = [];
url[0] = process.argv[2];
url[1] = process.argv[3];
url[2] = process.argv[4];
var data = [];
var remaining = url.length;
for(var i = 0; i < url.length; i++){
// create closure here to uniquely capture the loop index
// for each separate http request
(function(index) {
http.get(url[index], function (response){
response.setEncoding('utf8');
response.pipe(bl(function (err, chunk){
if(err){
console.log(err);
}
else{
data[index] = chunk.toString();
console.log(data[index]);
remaining -= 1;
if(remaining == 0) {
for(var j = 0; j < url.length; j++){
console.log(data[j]);
}
}
}
}));
});
})(i);
}
If you do much node.js programming, you will find that you probably want to learn how to use promises because they are very, very handy for controlling the flow and sequence of async operations.

Resources