Mailgun attachments not showing up - node.js

Using Nodejs, I've been able to temporarily store a file that was uploaded in a form to a location. From there, I wanted to use mailgun-js to send an email with that file attached.
I'm able to get the email to display an attachment, but the attachment (in my test case, I'm uploading a regular png file) will be broken. By broken, I mean this:
I'm not sure what is going on--but I can't seem to find anyone else who had my problem; so I'm sure it's something wrong I've done. I appreciate any and all help.
Edit: If I hardcode the path (i.e. I place an image in a folder and then set the attachment to that path) then it sends the attachment correctly and I can view it no problems.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var https = require('https');
var fs = require('fs-extra');
var busboy = require('connect-busboy');
var multer = require('multer');
var app = express();
var upload = multer(({ dest: __dirname + '/tmp/' }));
// view engine setup
app.set('port', (process.env.PORT || 5000));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(busboy());
// Used for accessing webpages without the .html extension!
var publicdir = __dirname + '/public';
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
}
else
next();
});
app.use(express.static(publicdir));
//end .html extension removal
var type = upload.single('file');
app.post('/submit', type, function(req, res, next) {
console.log("____ Clicked submit ____");
//whether or not this form will carry an attachment
var hasAttachment = (req.body.attachment == '') ? false : true;
//path of file
var target_path; //actual image
var tmp_path;
var name = req.body.name;
var email = req.body.email;
var subject = req.body.subject;
var message = req.body.message;
//if there is an attachment, handle getting the file
if (hasAttachment) {
tmp_path = req.file.path;
//The original name of the uploaded file stored in the variable target_path
target_path = __dirname + '/tmp/' + req.file.originalname;
//A better way to copy the uploaded file.
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
}
//Use validator to sanitize for valid emails
var validator = require('validator');
if (!validator.isEmail(email)) {
console.log("Not a valid email");
res.end();
return;
}
//Mailgun api stuff
var api_key = 'redacted';
var domain = 'redacted';
var mailgun = require('mailgun-js')({
apiKey: api_key,
domain: domain
});
//data for mailgun (to, from, name, etc.)
var data;
if (hasAttachment) {
console.log(target_path);
data = {
from: email,
to: 'myEmail#gmail.com',
subject: subject + ' - ' + name,
text: message,
attachment: target_path
};
} else {
data = {
from: email,
to: 'myEmail#gmail.com',
subject: subject + ' - ' + name,
text: message
};
}
console.log(data);
mailgun.messages().send(data, function (error, result) {
if (error) {
console.error(error);
return;
}
});
console.log("Sent an email!!!");
res.redirect('/contact');
//delete the files after sending the email
if (hasAttachment) {
fs.unlink(target_path);
fs.unlink(tmp_path);
}
});
var server = app.listen(app.get('port'), function() {
//nothing
}); //server closing-bracket
/**
* ERROR HANDLING
*/
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
console.error("***ERROR: " + err.message);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;

send() is asynchronous, and you are deleting the file before it's had a chance to finish.
Instead, delete the files in send callback once you are sure it has finished.
Update:
In addition to the above, your file copy is also happening asynchronously and you are attempting to transfer the file before the copy has completed. So make sure you wait for that:
dest.on("close", function(error, result) {
if (error) {
console.log("COPY ERROR", error);
// TODO: respond with some error result
} else {
mailgun.messages().send(data, function (error, result) {
// delete the files
if (hasAttachment) {
fs.unlink(target_path);
fs.unlink(tmp_path);
}
if (error) {
console.error(error);
// TODO: respond with some error result
} else {
console.log("Sent an email!!!");
res.redirect('/contact');
}
});
}
});
The above change will make your code work.
I presume you are copying the file so that the image will show up properly in the email. (Mailgun infers how to handle the attachment based on its file extension, and Multer's default temp filename doesn't include an extension.)
You can avoid doing the copy altogether by configuring Multer to retain the file extension.
https://github.com/expressjs/multer#storage

Related

NodeJS image not uploading and category name showing variable instead of value

I am working on a NodeJS style blog and for some reason, the variable for the category name shows up as #{category.name} whereas the other variable values actually show the values. Secondly, When I submit the image for the post, it does not upload the image. Any help to see if there might be some errors in my code would be greatly appreciated. Thank you in advance.
app.js
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var session = require("express-session");
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var expressValidator = require("express-validator");
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
var routes = require("./routes/index");
var posts = require("./routes/posts");
var categories = require("./routes/categories");
var app = express();
app.locals.moment = require("moment");
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
};
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// Express Session
app.use(
session({
secret: "secret",
saveUninitialized: true,
resave: true
})
);
// Express Validator
app.use(
expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split("."),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += "[" + namespace.shift() + "]";
}
return {
param: formParam,
msg: msg,
value: value
};
}
})
);
// Connect-Flash
app.use(require("connect-flash")());
app.use(function(req, res, next) {
res.locals.messages = require("express-messages")(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use("/", routes);
app.use("/posts", posts);
app.use("/categories", categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get("env") === "development") {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render("error", {
message: err.message,
error: {}
});
});
module.exports = app;
index.pug
extends layout
block content
if posts
each post, i in posts
.post
h1
a(href='/posts/show/#{post._id}')
=post.title
p.meta Posted in
a(href='/categories/show/#{post.category}') #{post.category} by #{post.author} on #{moment(post.date).format("MM-DD-YYYY")}
img(src='/images/#{post.mainimage}')
!=truncateText(post.body,400)
a.more(href='/posts/show/#{post._id}') Read More
addpost.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/posts/add', enctype="multipart/form-data")
.form-group
label Title:
input.form-control(name='title', type='text')
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value='#{category.name}') #{category.name}
.form-group
label Body
textarea.form-control(name='body', id='body')
.form-group
label Main Image:
input.form-control(name='mainimage', type='file')
.form-group
label Author:
select.form-control(name='author')
option(value='Erik Robles') Erik Robles
option(value='John Doe') John Doe
input.btn.btn-default(name='submit',type='submit',value='Save')
script(src='/ckeditor/ckeditor.js')
script
| CKEDITOR.replace('body');
addcategory.pug
extends layout
block content
h1=title
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post', action='/categories/add')
.form-group
label Name:
input.form-control(name='name', type='text')
input.btn.btn-default(name='submit',type='submit',value='Save')
posts.js
var express = require("express");
var router = express.Router();
var multer = require("multer");
var upload = multer({ dest: "./public/images" });
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/add", function(req, res, next) {
var categories = db.get("categories");
categories.find({}, {}, function(err, categories) {
res.render("addpost", {
title: "Add Post",
categories: categories
});
});
});
router.post("/add", upload.single("mainimage"), function(req, res, next) {
// Get Form Values
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
var date = new Date();
// Check Image Upload
if (req.file) {
var mainimage = req.file.filename;
} else {
var mainimage = "noimage.jpg";
}
// Form Validation
req.checkBody("title", "Title field is required").notEmpty();
req.checkBody("body", "Body field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var posts = db.get("posts");
posts.insert(
{
title: title,
body: body,
category: category,
date: date,
author: author,
mainimage: mainimage
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Post Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
index.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
/* GET home page. */
router.get("/", function(req, res, next) {
var db = req.db;
var posts = db.get("posts");
posts.find({}, {}, function(err, posts) {
res.render("index", { posts: posts });
});
});
module.exports = router;
categories.js
var express = require("express");
var router = express.Router();
var mongo = require("mongodb");
var db = require("monk")("localhost/nodeblog");
router.get("/show/:category", function(req, res, next) {
var posts = db.get("posts");
posts.find({ category: req.params.category }, {}, function(err, posts) {
res.render("index", {
title: req.params.category,
posts: posts
});
});
});
router.get("/add", function(req, res, next) {
res.render("addcategory", {
title: "Add Category"
});
});
router.post("/add", function(req, res, next) {
// Get Form Values
var name = req.body.name;
// Form Validation
req.checkBody("name", "Name field is required").notEmpty();
// Check Errors
var errors = req.validationErrors();
if (errors) {
res.render("addpost", {
errors: errors
});
} else {
var categories = db.get("categories");
categories.insert(
{
name: name
},
function(err, post) {
if (err) {
res.send(err);
} else {
req.flash("success", "Category Added");
res.location("/");
res.redirect("/");
}
}
);
}
});
module.exports = router;
If I am missing anything, please let me know so I can make the appropriate edits. Again, Thank you.
P.S. By structure is:
routes
categores.js
index.js
posts.js
views
addcategory.pug
addpost.pug
error.pug
index.pug
layout.pug
app.js
The code I was using is old (circa 2016) and no longer works. In calling the variable name, you must remove the curly braces, hash and quotes from the first option variable. Here is how the code should read in the categories options section:
addpost.pug
.form-group
label Category
select.form-control(name='category')
each category, i in categories
option(value=category.name) #{category.name}
I hope this answer helps someone struggling with the same issue.

Node.js Retrieve URL Parameters from Server

I need to pass a parameter (qItems) in XMLHttpRequest.open:
index.html (app.listen(8080);)
var qItems= 8;
var url= 'ItemsList';
var xhr = new XMLHttpRequest();
var tag = document.getElementById("insertHere");
tag.innerHTML = "Loading...";
xhr.open("GET", url+"?qItems="+qItems, true);
xhr.onreadystatechange = function() {
display(tag, xhr);
}
xhr.send(null);
But on Server side (server.js) use static URLs:
var express = require('express');
var bodyParser = require('body-parser');
var directory = require('serve-index');
var sqlite3 = require('sqlite3').verbose();
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', __dirname);
app.set('view engine', 'pug');
var db = new sqlite3.Database('./data/DB.sqlite',function(err){
if (err) {
console.log(err.message);
}
console.log('Connected to DB!');
});
app.get('/ItemsList', function(req, res) {
db.all("SELECT rowid, iName, iDescrip FROM Items", function(err, row) {
if (err !== null) {
res.status(500).send("An error has occurred: " + err);
} else {
res.render('ItemsList.pug', {
items: row
}, function(err, html) {
res.status(200).send(html)
});
}
});
});
I try (server.js):
app.get('/ItemsList?qItems='+qItems, function(req, res) {...}
But I get error: qItems undefined (from node.js)
Is there any way to get query parameters from Server side?
You don't need to implement a different handler for url with query params, ItemsList/qItems=xxx, query params are available to /ItemsLists GET handler in req.query.
app.get('/ItemsList', function(req, res) {
// You can access qItems from query params
var qItems = req.query.qItems
...
}

I seem to get a "new module instance" when calling require

I am trying to get MongoDB to work with Express.js. I have followed this article and created a file db/index.js that provides functions for creating a database connection and returning the connection instance. In app.js I require that file first, then call its function connect, which successfully connects to the database.
However, when I require the file db/index.js later in another file routes/users.js, the database reference it returns is null, although I expected it to be the same reference that I got when I connected in app.js. Doesn't require always return the same instance of the module that is returned on the first call to require? What am I doing wrong?
EDIT: I understand that because the call db.connect is asynchronous, the value of db in users.js might in theory be null before the connecting function returns. However, I have verified via testing that even if connection is successfully created, db is still null when I do a POST request to path /users.
Here are the 3 relevant files.
app.js (execution starts here)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// configuration environment based on process.env.NODE_ENV environment variable
var config = require('./config');
var db = require('./db');
var app = express();
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);
// Connect to Mongo on start
db.connect(config.dbUrl, function (err) {
if (err) {
console.log('Unable to connect to ' + config.dbUrl);
process.exit(1);
} else {
console.log('Connected to ' + config.dbUrl);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/tests', express.static(__dirname + '/test'));
app.use('/lib/jasmine-core', express.static(__dirname + '/node_modules/jasmine-core/lib/jasmine-core'));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
db/index.js
var MongoClient = require('mongodb').MongoClient;
var state = {
db: null
};
exports.connect = function (url, done) {
if (state.db)
return done();
MongoClient.connect(url, function (err, db) {
if (err)
return done(err);
state.db = db;
done();
})
}
exports.get = function () {
return state.db;
}
exports.close = function (done) {
console.log('db close');
if (state.db) {
state.db.close(function (err, result) {
state.db = null;
done(err);
})
}
}
exports.createIndexes = function () {
if (state.db) {
state.db.collection('events').createIndex(
{'id': 1},
{unique: true});
}
}
routes/users.js
var express = require('express');
var router = express.Router();
var db = require('../db').get();
router.post('/', function (req, res, next) {
//
// Problem: Every time this function is called, db is null!
//
var users = db.collection('users');
var userToAdd = req.body;
users.findOne({username: userToAdd.username}).then(function (foundUser) {
if (foundUser.length === 0) {
res.status(400).json({error: 'Username is already in use'});
} else {
// TODO: ADD USER
res.json(foundUser);
}
})
.catch(function (err) {
console.log(err);
res.status(500).json({error: 'Database error.'});
});
});
module.exports = router;
For the record, you are not receiving "new" instance, following explanation will help you make sense what is happening.
Notice that you are requiring your routes before connecting to your db via db.connect. i.e.
//Called before db.connect is called.
//so at this point in time, your db.get will return null, make sense?
//because in your users.js your are directly calling var db = require('../db').get();
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);
// Connect to Mongo on start
db.connect(config.dbUrl, function (err) {
if (err) {
console.log('Unable to connect to ' + config.dbUrl);
process.exit(1);
} else {
//after this point in execution, calling db.get will return actual db and not null.
console.log('Connected to ' + config.dbUrl);
}
});
There are two solutions to your problem.
1.
Restructure your app.js code like this will solve your issue.
// Connect to Mongo on start
db.connect(config.dbUrl, function (err) {
if (err) {
console.log('Unable to connect to ' + config.dbUrl);
process.exit(1);
} else {
//As now we have db initialised, lets load routes.
var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/', routes);
app.use('/users', users);
console.log('Connected to ' + config.dbUrl);
}
});
2
Leave your app.js as it is and make changes in your routes, for e.g., users.js use db as following,
var express = require('express');
var router = express.Router();
var dbFetcher = require('../db');
router.post('/', function (req, res, next) {
//
// Problem: Every time this function is called, db is null!
var db = dbFetcher.get();
var users = db.collection('users');
var userToAdd = req.body;
users.findOne({username: userToAdd.username}).then(function (foundUser) {
if (foundUser.length === 0) {
res.status(400).json({error: 'Username is already in use'});
} else {
// TODO: ADD USER
res.json(foundUser);
}
})
.catch(function (err) {
console.log(err);
res.status(500).json({error: 'Database error.'});
});
});
module.exports = router;
I hope it makes sense and helps!
The line
var db = require('./db');
declares a new variable which only exists within the scope of that file. When you make similar declaration in your routes/user file, you create a completely new db variable, which means that the connect method was never run and so the state property was never changed.

Get Response Doesnt Initialize to a local variable

I use the following code to accept the user sms from my android app and send back the result to the user after making specified get request to some site.the expected output that the user should get is "thanks for your message"+[the response of get request]..what i get is "Thanks for your message undefined"it seems that my variable "body" doesnt get initialized with the GET response.please help
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello Cruel World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
var request = require("request");
var body;
request("http://www.google.com", function(error, response, data) {
body = data;
});
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message! " + body}
]
});
}
res.status(200).end();
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
please help me to resolve the problem..the answer posted here doesnt seems working http://goo.gl/GYgd6Z,help by taking my code specified here as example...please
The res.json line will execute before the callback from request, so body won't be populated - change like this:
request("http://www.google.com", function(error, response, data) {
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message! " + data}
]
});
res.status(200).end();
});
This ensures that the res.json is executed after the response from request().

How to do csv file export and download on request [duplicate]

How can I download a file that is in my server to my machine accessing a page in a nodeJS server?
I'm using the ExpressJS and I've been trying this:
app.get('/download', function(req, res){
var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');
res.setHeader('Content-Length', file.length);
res.write(file, 'binary');
res.end();
});
But I can't get the file name and the file type ( or extension ). Can anyone help me with that?
Update
Express has a helper for this to make life easier.
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
Old Answer
As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
res.setHeader('Content-type', 'video/quicktime');
If you want something more in-depth, here ya go.
var path = require('path');
var mime = require('mime');
var fs = require('fs');
app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.
Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.
Use res.download()
It transfers the file at path as an “attachment”. For instance:
var express = require('express');
var router = express.Router();
// ...
router.get('/:id/download', function (req, res, next) {
var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
var fileName = "report.pdf"; // The default name the browser will use
res.download(filePath, fileName);
});
Read more about res.download()
For static files like pdfs, Word docs, etc. just use Express's static function in your config:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
And then just put all your files inside that 'public' folder, for example:
/public/docs/my_word_doc.docx
And then a regular old link will allow the user to download it:
My Word Doc
Here's how I do it:
create file
send file to client
remove file
Code:
let fs = require('fs');
let path = require('path');
let myController = (req, res) => {
let filename = 'myFile.ext';
let absPath = path.join(__dirname, '/my_files/', filename);
let relPath = path.join('./my_files', filename); // path relative to server root
fs.writeFile(relPath, 'File content', (err) => {
if (err) {
console.log(err);
}
res.download(absPath, (err) => {
if (err) {
console.log(err);
}
fs.unlink(relPath, (err) => {
if (err) {
console.log(err);
}
console.log('FILE [' + filename + '] REMOVED!');
});
});
});
};
In Express 4.x, there is an attachment() method to Response:
res.attachment();
// Content-Disposition: attachment
res.attachment('path/to/logo.png');
// Content-Disposition: attachment; filename="logo.png"
// Content-Type: image/png
'use strict';
var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');
var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());
app.use(function (req, res, next) {
req.setTimeout(3600000)
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());
if (req.method === 'OPTIONS') {
res.write(':)');
res.end();
} else next();
});
function readApp(req,res) {
var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
filePath = "/home/sony/Documents/docs/";
fs.exists(filePath, function(exists){
if (exists) {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition" : "attachment; filename=" + file});
fs.createReadStream(filePath + file).pipe(res);
} else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end("ERROR File does NOT Exists.ipa");
}
});
}
app.get('/read-android', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
app.get('/read-ios', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
you can use res.sendFile()... the Sample-download.xlsx should be in the same directory as this function.
const downloadFile = (req,res) => {
var options = {
root: path.join(__dirname),
};
let fileName = "Sample-download.xlsx";
res.sendFile(fileName, options, function (err) {
if (err) {
console.log(err);
return res.status(500).json({ success: false, message: "internal server error. please try again later" });
} else {
console.log("Sent:", fileName, "at", new Date().toString());
}
});
}

Resources