Node File upload issue - javascript

I am constantly getting the printed out message of "No File Upload" Failed when I select my image and hit upload. It never goes to true..
As you can see, I am not actually uploading here. Just testing the req.files is there something wrong in my router.post? Any input would be appreciated.
router.post('/upload', async (req, res) => {
try {
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
} else {
res.send({
status: true,
message: 'Files are uploaded',
data: data
});
}
} catch (err) {
res.status(500).send(err);
}
})
module.exports=router

can you share your controller file of it and also you are using async function but not defining await inside of that function,must have to use 'await' when executing async function.

here is the controller file AAmir
let fs = require('fs');
let async = require('async');
function uploaddownFiles(connection, fromFolder, toFolder, sftpmethod) {
return new Promise((resolve, reject) => {
// Getting all file list in given folder of local machine
let fileList = fs.readdirSync(fromFolder);
// filter only files not folders
fileList = fileList.filter(file => {
if (file.includes('.')) return true;
return false;
});
console.log('Total files: ', fileList.length)
if (!fileList.length) return reject('No file to send')
connection.sftp(function (err, sftp) {
if (err) return;
async.eachOfSeries(fileList, (file, key, cb) => {
let moveFrom = `${fromFolder}/${file}`;
let moveTo = `${toFolder}/${file}`;
if (sftpmethod=== 'put')
sftp.fastPut(moveFrom, moveTo, {}, function (uploadError) {
if (uploadError) return cb(uploadError);
console.log("Successfully Uploaded", file);
cb();
});
else if (sftpmethod === 'get')
sftp.fastGet(moveFrom, moveTo, {}, function (uploadError) {
if (uploadError) return cb(uploadError);
console.log("Successfully Downloaded", file);
cb();
});
}, function (err) {
if (err) {
console.log(err);
return reject(err);
} else {
console.log('all files have been uploaded/downloaded');
return resolve();
}
})
});
});
}

Related

zip and download folders to local using nodejs

How to zip and download folder from D:/downloads path. As a 1st step, I was able to create a folder inside 'downloads' with dummy content. As a next step I want to zip and download that folder.
async downloadFolder(selectedProduct) {
try {
let completeZip = await this.jobService.zipBlobs(selectedProduct.path, this.role).toPromise();
if(completeZip['status']=='success'){
let download = await this.jobService.downloadBlobs(selectedProduct.path, this.role).toPromise();
console.log(download)
}
} catch (error) {
console.log(error);
}
}
API:
Once file is written , I want to zip that folder and download that folder to local but nothing happens
exports.zipBlobs = async function (req, res) {
var userrole = req.body.userrole;
var path = req.body.path;
fileUploadPath="d:/downloads";
blobService.listBlobsSegmentedWithPrefix(containerName, path, null, (err, data) => {
if (err) {
reject(err);
} else {
data.entries.forEach(entry => {
console.log(entry.name);//'155ce0e4-d763-4153-909a-407dc4e328d0/63690689-e183-46ae-abbe-bb4ba5507f1a_MULTI_0_3/output/res2/res2.fcs';
if (fs.existsSync(fileUploadPath)) {
var sourceFilePath = fileUploadPath +'/'+entry.name ;
if (!fs.existsSync(sourceFilePath)) {
fs.mkdir(require('path').dirname(sourceFilePath), { recursive: true }, (err) => {
if (err) {
console.log("Failed :" + err);
}
else{
console.log('folder created,create file');
const fstream = fs.createWriteStream(sourceFilePath);
fstream.write('fileContent');
fstream.end();
fstream.on("finish", f => {
console.log('finish',f) ;
});
fstream.on("error", e => {
console.log('error',e);
});
}
});
}else{
console.log('folders already exists,create file');
const fstream = fs.createWriteStream(sourceFilePath);
fstream.write('fileContent');
fstream.end();
fstream.on("finish", f => {
console.log('finish',f) ;
});
fstream.on("error", e => {
console.log('error',e);
});
}
}else{
console.log('downloads folder does not exists!')
}
});
}
});
}
API to zip and download folder :
exports.downloadFolders = async function (req, res) {
var userrole = req.body.userrole;
var path = req.body.path;
try {
const folderpath = 'D:\downloads\622b6a148a813f18b8b2de81';
require('child_process').execSync(`zip -r archive *`, {
cwd: folderpath
});
// does not create zip, neither downloads
res.download(folderpath + '/archive.zip');
return;
}catch(error_1) {
res.status(200).json({
status: error_1
});
return;
}
}
In Javascript strings, backslashes must be doubled:
const folderpath = 'D:\\downloads\\622b6a148a813f18b8b2de81';
Without doubling them, you effectively get
const folderpath = 'D:downloads22b6a148a813f18b8b2de81'
because '\d' === 'd' and '\6' is a non-printable character.
You can also write the result of zip to the standard output and pipe it into the response object:
res.set("Content-Disposition", "attachment;filename=archive.zip");
require("child_process").exec("zip -r - *", {
cwd: folderpath
}).stdout.pipe(res);
This is something I used in one of my projects where I needed the whole directory downloaded as zip:
require the following library:
const zipdir = require('zip-dir')
Then, when you need to download the zip, call it as follows:
zipdir(
'D:/downloads/622b6a148a813f18b8b2de81',
{ saveTo: 'D:/downloads/622b6a148a813f18b8b2de81/archive.zip' },
(err, buffer) => {
if (err) throw err;
console.log('New zip file created!');
}
);
Following is the API signature:
app.get('/api/zip', function (req, res) {
//create new zip
zipdir(
'D:/downloads/622b6a148a813f18b8b2de81',
{ saveTo: 'D:/downloads/622b6a148a813f18b8b2de81/archive.zip' },
(err, buffer) => {
if (err) throw err;
console.log('New zip file created!');
res.download('D:/downloads/622b6a148a813f18b8b2de81/archive.zip');
}
);
});

Fs operations with Yargs

I have to perform some operations with Yargs.For example-
1- Write in a file using fs module and for every write operation need to create a new file,
2-You must take i/p from user as fileName and keep saving fileNames in one array (array part is not done), in one separate text file
3-Next time when user enters the same fileName , if it exists ask again to give new fileName , and then same as Point 1.
I am facing issues with point 2, how to write as an array in text file, and how to call 'Please provide the fileName' again if user keeps on giving existing fileName.
So far I have done this-
const argv = require('yargs').argv;
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
if (argv._[0] == 'write') {
rl.question('Please provide the filename:=>', (fileName) => {
fs.writeFile('fileNameList.txt', fileName, err => {
if (err) {
console.log('Error occured');
return;
}
fs.writeFile(fileName, 'Hello', err => {
if (err) {
console.log('Error occurred');
return
}
});
});
rl.close();
});
}
else {
console.log('No write operation');
}
so, when user executes it like node index.js write, it will ask the fileName
you need to refactor your code into methods to show intent properly:
Check if file exists
function ifFileExists(filepath) {
try {
fs.accessSync(filepath, fs.constants.F_OK);
return true;
} catch (e) {
return false;
}
}
Ask for user input
function askForUserInput(message) {
rl.question(message, (fileName) => {
if (ifFileExists(fileName)) {
askForUserInput('File already exists, Please provide a new filename:=>');
} else {
writeToFile(fileName);
rl.close();
}
});
}
write to file
function writeToFile(fileName) {
fs.writeFile('fileNameList.txt', fileName, err => {
if (err) {
console.log('Error occured');
return;
}
fs.writeFile(fileName, 'Hello', err => {
if (err) {
console.log('Error occured');
return
}
});
});
}
use it
if (argv._[0] == 'write') {
askForUserInput('Please provide the filename:=>');
}
else {
console.log('No write operation');
}
your logic to write filenames in fileNameList.txt looks correct.
Have a look at this solution and see, to me it looks like since you have file name as entry you can simply write it to the file and when reading from file add to an array
node.js - how to write an array to file
and
node.js: read a text file into an array. (Each line an item in the array.)
const argv = require("yargs").argv;
const fs = require("fs");
const readline = require("readline");
function ifFileExists(fileName) {
return new Promise((resolve, reject) => {
fs.readFile("array.txt", function (err, arrayData) {
if (err) {
if (err.code === "ENOENT") {
handleWhenArrayFileNotFound(reject, resolve);
} else {
reject("file read error");
}
}
if (arrayData) {
handleWhenArrayExists(arrayData, resolve, fileName);
}
});
});
function handleWhenArrayFileNotFound(reject, resolve) {
let content = fileName;
content += "\n";
fs.writeFile("array.txt", content, (error) => {
if (error) {
console.log("Error occured");
reject("file write error");
}
rl.close();
resolve("created");
});
}
function handleWhenArrayExists(arrayData, resolve, fileName) {
if (fileNamePresentInArray(arrayData, fileName)) {
askForNewName("File already exists, Please provide a new filename:=>");
} else {
resolve("create file");
}
}
}
function fileNamePresentInArray(arrayData, fileName) {
var array = arrayData.toString().split("\n");
return array.includes(fileName);
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function askForNewName(message) {
rl.question(message, (fileName) => {
fs.readFile("array.txt", function (err, arrayData) {
if (err) {
console.log("array.txt not found");
}
if (arrayData) {
if (fileNamePresentInArray(arrayData, fileName)) {
askForNewName(
"File already exists, Please provide a new filename:=>"
);
} else {
writeToFile(fileName);
rl.close();
}
}
});
});
}
function askForUserInput(message) {
rl.question(message, (fileName) => {
ifFileExists(fileName)
.then((res) => {
writeToFile(fileName, res);
})
.catch((err) => {
console.log(err);
});
});
}
function writeToFile(fileName, data) {
if (data !== "created") {
let content = fileName;
content += "\n";
fs.appendFile("array.txt", content, (err) => {
if (err) console.log(err);
});
}
fs.writeFile(fileName, "You are awesome", (err) => {
if (err) {
console.log("Error occured");
}
});
}
if (argv._[0] == "write") {
askForUserInput("Please provide the filename:=>");
} else {
console.log("No write operation");
}

error in getting the response, if nodejs server send response after some delay

I am trying to upload the image, and then nodeJS server send the path of that image folder back as a response.
But When I sending the response after performing some task, nothing happening on angular-side.
this is my component.ts file.
uploadImage() {
const formData = new FormData();
formData.append('photo', this.image);
const obj$ = this.userService.uploadData(formData);
obj$.subscribe(data => {
console.log(data); //// nothing happening.
if (data.success) {
this.uploadForm.patchValue({
document: data.url
});
}
});
}
and my service.ts
uploadData (uploadImage) {
return this.http.post<UploadPhoto>('/user/upload', uploadImage);
}
and my app.js
router.post('/upload' ,upload.single('photo'), (req,res) => {
console.log(req.file);
const body = req.file;
cloudinary.uploader.upload(body.path, (err, result) => {
if (err) {
console.log(err);
return;
}
console.log(result);
res.status(200).json({
url: result.url,
success: true
});
});
});
But when I am sending response without performing any task, it works fine like
router.post('/upload' ,upload.single('photo'), (req,res) => {
console.log(req.file);
const body = req.file;
res.status(200).json({
url: 'hello',
success: true
})
});
I don't know why is this happening.
Please someone help me.
When an error occurs in your uploader you're returning the error to the console and then ending execution. If there is an error in the asynchronous method you must pass it to the next() function so that express can handle it.
router.post('/upload' ,upload.single('photo'), (req,res, next) => {
console.log(req.file);
const body = req.file;
cloudinary.uploader.upload(body.path, (err, result) => {
if (err) {
console.log(err);
next(err);
}
else {
console.log(result);
res.status(200).json({ url: result.url, success: true });
}
});
});

NodeJS and Mocha :Test is getting passed, instead of getting failed

Below program is to read all the files under a folder and check if all the files contains email information.
The below test should be failed(i.e.., promise to be rejected and status should be failed) when the condition in the second "if" statement is true. Execution is getting stopped, but the test is getting passed instead of getting failed.
So, How do i make the below test fail.
Thanks in Advance.
var checkFileContent = function(directory) {
var results = [];
fs.readdir(directory, function(err, list) {
// if (err) return done(err);
console.log("The folder or list of file names : " + list);
var i = 0;
(function next()
{
var file = list[i++];
// if (!file) return done(null, results);
file = directory + '/' + file;
fs.stat(file, function(err, stat)
{
if (stat && stat.isDirectory())
{
checkFileContent(file, function(err, res)
{
results = results.concat(res);
next();
});
} else
{
fs.readFile(file, "utf8", function(err, data)
{
// if ( err )
// { throw err;}
console.log(file +" file content is");
console.log(data);
console.log( data.toLowerCase().indexOf('email'));
return new Promise((resolve, reject) => {
if(data.toLowerCase().indexOf('email') != -1)
{
return reject(file + 'contains email ');
}
else
{
return new Promise((resolve, reject) =>
{
fs.readFile(file, "utf8", function(err, data)
{
// if ( err )
// { throw err;}
console.log(file +" file content is");
console.log(data);
console.log( data.toLowerCase().indexOf('email'));
//return newfunc(file,data);
if(data.toLowerCase().indexOf('email') != -1)
{
reject(file + 'contains email ');
}
else
{
console.log(file + 'doesnt contain email');
resolve(true);
}
}).catch ((err) =>
{
//Execution is getting stopped here, but the test is getting passed instead of getting failed.
return reject(err);
});
});
results.push(file);
//console.log("List of files under the current Log folder are : " + results);
next();
} // else closure
}); // fs.stat() closure
})(); });
}
The above function is being called from another JS File using Mocha as shown below :
it('should read Log files', function () {
return ----
.then((abc) => {
------
}).then(()=>
{
return JSFileName.checkFileContent(directory);
}).catch((err) => {
return Promise.reject(err);
})
})

node.js ignores awaitZip building with express

I want to fetch icon PNGS from gridfs out of our mongodb database with mongoose. These icons then should be zipped and served at a specific route.
My current code is as follows:
var zip = require("node-native-zip");
async function getZipFile() {
//get the events out of the DB
db.Category.find({}).populate('icons.file').exec(async function (err, cats) {
if (err) {
//oh oh something went wrong, better pass the error along
return ({
"success": "false",
message: err
});
}
else {
//all good, build the message and return
try {
const result = await buildZip(cats);
return ({
"success": "true",
message: result
});
}
catch (err) {
console.log("ZIP Build Failed")
}
}
});
}
async function buildZip(cats) {
let archive = new zip();
for (let i = 0; i < cats.length; i++) {
cats[i].icons.forEach(function (icon) {
if (icon.size === "3x") {
db.Attachment.readById(icon.file._id, function (err, buffer) {
if (err)
return;
archive.add(cats[i]._id + ".png", buffer);
});
}
});
//return when everything is done
if (i === cats.length - 1) {
return archive.toBuffer();
}
}
}
module.exports =
{
run: getZipFile
};
I don't want to build the zip before runtime, as I want to rename the icons acording to the category ID. I tried going for a async/await structure, but my callback is being returned before the building of the zip file even started.
I'm calling the function with
case 'categoryZip':
categoryHelper.getZipFile.run().then((result) => {
callback(result);
});
break;
This should (as far as I understood it) fire the callback when the zipping is done, but I think I'm missing something essential here.
I wrapped both your callback methods into promises, and also awaited your double for-loop of callbacks in parallel using Promise.all() since they don't rely on each other and I assume they don't need to be in any particular order in the zip file:
async function getZipFile() {
//get the events out of the DB
return new Promise((resolve, reject) => {
db.Category.find({}).populate('icons.file').exec(async function(err, cats) {
if (err) {
//oh oh something went wrong, better pass the error along
reject({
success: false,
message: err
});
} else {
//all good, build the message and return
try {
const result = await buildZip(cats);
resolve({
success: true,
message: result
});
} catch (err) {
console.log("ZIP Build Failed")
reject({
success: false,
message: err
});
}
}
});
});
}
async function buildZip(cats) {
let archive = new zip();
await Promise.all(
cats.map(cat => Promise.all(cat.icons
.filter(icon => icon.size === '3x')
.map(icon => new Promise((resolve, reject) => {
db.Attachment.readById(icon.file._id, function(err, buffer) {
if (err) return reject(err);
archive.add(cat._id + ".png", buffer);
resolve();
});
}))
))
);
return archive.toBuffer()
}

Categories

Resources