Export table data to excel from server side in nodejs - node.js

I am using json2xls npm, here is my code below:
exports.exportContactsXlsx = function (req, res) {
var data = req.body;
var xls = json2xls(data);
fs.writeFileSync('data.xlsx', xls, 'binary');
}
After clicking export button, successfully i got "data.xlsx" file, but when i hit Export button in UI, i want to get that data.xlsx is downloading in bottom left corner of chrome browser.
How to do that?

To setup a download link, on your anchor tag use the download attribute, and the src will be downloaded in the bottom corner

Related

How to create a url that opens a tab downloads a file and closes the tab

I want to create an URL that when clicked upon opens a tab, downloads a file, and closes that tab. Do you guys know how to do it?
Following is an example: https://cdn.discordapp.com/attachments/850262728428748830/937385812671209502/vineboom.ogg
I am quite new to this and overwhelmed to know where to start. Can somebody assist me with this?
I tried messing with Anchor tag but that is not the answer. According to my research figured it has something to do with NodeJS and ExpressJS. Still no idea of what to do.
Create require variables as shown and then created a function with whatever name you like, here I am using "onLoad" as the name. This function just checks for the file name in the URL's file parameter specified then tries to find it in the server.
var url_string = window.location; //window.location.href
var url = new URL(url_string);
var file = url.searchParams.get("file");
var dFile = file;
function onLoad() {
var hiddenElement = document.createElement('a');
hiddenElement.href = `${dFile}`;
hiddenElement.target = '_blank';
hiddenElement.download = `${dFile}`;
hiddenElement.click();
close()
}
Make sure to add onLoad function into the body with event listener of "onload"
<!DOCTYPE html>
<body onload="onLoad()">
</body>

Unable to use res.send and res.download in Node/Express due to headers already being set

I am new to Node, and I am trying to make it so that when I go to 'localhost:1337/download/open' it renders a webpage, as well as download a file.. I understand that you can only set a header once (that is the error I am getting), but what is the easiest way to both render html AND download a file? Code below:
const express = require('express');
const app = express();
app.get('/download/open', function (req, res) {
let file = `${__dirname}/downloads/Open Tasks.csv`;
res.download(file);
res.send("words");
})
app.listen(1337, function (err) {
if (err) {
console.log(err)
return
}
console.log(`App running. listening on: http://localhost:1337`);
});
Error:
Error: Can't set headers after they are sent.
Thank you in advance.
I was able to figure out what I was trying to do. Instead of trying to render a whole new page AND download a file, I needed to dedicate a route to just a download through the use of an <a></a> tag.
For instance, if I have a webpage at 'http://localhost:1337' that has a link on it like:
Download Open Tasks
Download Open Tasks
Then in node.js I have a route for 'download/open' like so:
app.get('/download/open', function (req, res) {
let file = `${__dirname}/downloads/Open Tasks.csv`;
res.download(file);
})
It will not open a new page (like I thought it needed to) it will just download the file.
IMO, I would suggest you should do the following to achieve your goal:
render the HTML result for "GET http://localhost:1337/download/open"
In the HTML file /download/open, put AJAX block to invoke download file operation
(Download a file by jQuery.Ajax)
$(document).ready(function(){
//code to invoke download file....
});

Can't show folder selection dialog in Electron

How can I show a folder selection dialog in NodeJS or ElectronJS?
Currently, I'm using nw-dialog:
const dialog = require('nw-dialog')
dialog.openFileDialog(function() {
alert('test')
})
However, I am getting an exception:
ReferenceError: document is not defined
nw-dialog is intended to be used with nw, not with Electron.
If you want to open dialogs in Electron, you should use Electron's dialog module:
const {dialog} = require('electron')
console.log(dialog.showOpenDialog({properties: ['openFile', 'openDirectory', 'multiSelections']}))

webdriverio (javascript) - upload an image

so i'm writing a test to upload an image with webdriverio javascript
http://webdriver.io/api/utility/chooseFile.html
I'm guessing this is the command I use, can someone provide me with an example on how to do this?
thanks
This is the example in the integration test.
describe('choosing a file in an <input type=file>', function() {
before(h.setup());
var path = require('path');
var toUpload = path.join(__dirname, '..', '..', 'fixtures', 'cat-to-upload.gif');
it('uploads a file and fills the form with it', function() {
return this.client.chooseFile('#upload-test', toUpload).catch(function(err) {
assert.ifError(err);
}).getValue('#upload-test').then(function(val) {
assert.ok(/cat\-to\-upload\.gif$/.test(val));
});
});
it('errors if file does not exists', function() {
return this.client.chooseFile('#upload-test', '$#$#940358435').catch(function(err) {
assert.notEqual(err, null);
});
});
});
client.chooseFile(selector,localPath).then(callback);
The first parameter is the selector (id of your input field), second parameter is path to the file you will upload.
You just need to click submit to upload the file. Note that it probably won't work everywhere. The required file endpoint is not even documented in the Selenium project.
To upload image,
First create a folder named 'resources' in your project directory and save the image in that directory
Use the below code to upload the file . In the third line, you need to replace the selector with the one on your application. Please note that if there is a button like "Upload" or "Add Photo" in the application, you need not perform click on this button before adding the below code.
var path = require("path");
var toUpload = path.join(__dirname, "..", "resources",
"CompanyPic.jpg");
browser.chooseFile('input[type="file"]', toUpload);

What is happening to my file with res.download in Express.js?

I'm working on an app that creates a PDF document on the server, then displays a Download Here button. When I click the button, the process appears to work. When I inspect the Network>Preview and Network>Headers tabs in the Chrome console I can see that the file has definitely been returned.
The problem is, it does not display and it does not offer the option to save. Am I missing a client side step here? My preferred outcome is either to give the user the option to save the file or to automatically begin the download to their default path.
Here is relevant the server code:
exports.show = function(req, res) {
var file = req.params.id;
var filePath = __dirname + '../../../lib/completedforms/';
var thisPath = path.resolve(filePath + file);
res.attachment(thisPath);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader("Content-Disposition", "attachment");
res.download(thisPath);
};
Thanks in advance for any guidance here.
There's no need for both res.attachment() AND res.download(). Just use the latter.
Also, res.download() already sets the Content-Disposition header, so you can remove that too.
You can also simplify your path generation:
var thisPath = path.resolve(__dirname, '../../../lib/completedforms/', file);
Although you should probably sanitize file and/or check that thisPath is not some location where it shouldn't be. This will prevent someone from supplying a potentially malicious req.params.id value like ../../../../../../../etc/passwd.

Resources