Routing on NodeJS Express - javascript

I'm developing a server in NodeJS with Express, but the web structure is a little bit complicate (I didn't do it, and I can't change it either).
The flow is something like this:
Node server receives a call like https://localhost/**{id}**.
The ID received is the folder's name where all files (html, js, css,
etc) are stored. By default, it returns index.html.
File structure of any web doesn't have a strict logic, means that could be more views at the same level the index.html is or in folders, wherever the clients wanted to develop them.
The issue I'm having is how to route the files correctly. Since I'm receiving the ID only when the index it's called, I couldn't figure out how to route links like View 1 or even the javascript files calls <script src='scripts/someGreatFunctions.js'></script> since they could also be in the root or in a folder (even the two things at the same time).
My server.js file:
const express = require('express');
const https = require('https');
const fs = require('fs');
const app = express();
const config = require('./config');
var webId;
var options = {
key: fs.readFileSync(config.paths.certificate.key),
cert: fs.readFileSync(config.paths.certificate.crt),
requestCert: false,
rejectUnauthorized: false
};
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
res.setHeader("Access-Control-Allow-Headers", "Accept, Access-Control-Allow-Headers, Access-Control-Request-Headers, Access-Control-Request-Method, Authorization, Content-Type, Origin, X-Requested-With");
next();
});
app.get('/scripts/:script', function(req, res) {
res.sendFile(req.params.script, {root: config.paths.webs + webId + '/scripts'});
});
app.get('/:script.js', function(req, res) {
res.sendFile(req.params.script + '.js', {root: config.paths.webs});
});
// This routes correctly the index
app.get('/:id', function(req, res) {
webId = req.params.id;
res.sendFile('index.html', {root: config.paths.webs + webId});
});
// This DID NOT work
app.get('/:id/:page', function(req, res) {
//Some code here...
});
https.createServer(options, app).listen(443, function() {
console.log("NodeJS secure server started at port 443");
});

I am also in a learning phase. Hope this will help.
app.get('/test/:id/:page', function(req, res, next) {
let id = req.params.id;
let page = req.params.page;
console.log('The id: ' + id);
console.log('The page: ' + page);
});

I finally got the answer. Seems like it's very important the order in which gets are declared. Also, I used a regular expression to make it a little more generic.
/**
* HTTP GET for files (.html, .js, etc.) from another folder level
*/
app.get('/:id/:folder/:file', function(req, res) {
if (typeof(webId) === undefined) {
webId = req.params.id;
}
let folder = req.params.folder;
let file = req.params.file;
res.sendFile(file, {root: config.paths.webs + webId + '/' + folder});
});
/**
* HTTP GET for .js files from the base path
*/
app.get(/\/\w+.\b(js)/, function(req, res) {
let lastBar = req.url.lastIndexOf('/');
let script = req.url.substr(lastBar);
res.sendFile(script, {root: config.paths.webs});
});
/**
* HTTP GET for index page
*/
app.get('/:id', function(req, res) {
webId = req.params.id;
res.sendFile('index.html', {root: config.paths.webs + webId});
});
/**
* HTTP GET for view from base path
*/
app.get('/:id/:page', function(req, res) {
if (typeof(webId) === undefined) {
webId = req.params.id;
}
let page = req.params.page;
res.sendFile(page, {root: config.paths.webs + webId});
});

Related

reloading the deep route after removing the '#' from url in express angular app throwing error [duplicate]

I would like to rewrite my URLs on my ExpressJS website. I've used this plugin, https://github.com/joehewitt/express-rewrite, but it doesn't work...
However, I might have made a mistake...
My app.js file :
var express = require('express')
, index = require('./routes/index.js')
, admin = require('./routes/admin.js')
, contact = require('./routes/contact.js')
, posts = require('./routes/posts.js')
, http = require('http')
, path = require('path')
, hash = require('./auth').hash
, db = require('./models')
, favicons = require('connect-favicons')
, rewriter = require('express-rewrite');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon(__dirname + '/public/images/FAVICON.ico'));
app.use(favicons(__dirname + '/public/images/apple-touch-icon.png'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.cookieSession({
secret: 'SECRET',
cookie: { access: false }
})
);
app.use(rewriter);
app.use(app.router);
app.use(function(req, res, next){
res.render('404.jade', {
title: "404 - Page Not Found",
showFullNav: false,
status: 404,
url: req.url
});
});
});
app.configure('development', function () {
app.use(express.errorHandler());
});
app.get('/', index.index);
app.get('/toto', rewriter.rewrite('/heytoto'));
db.sequelize.sync().complete(function(err) {
if (err) {
throw err
} else {
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'))
})
}
});
My error message :
Express
500 TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'match'
at Object.rewriter [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express-rewrite/rewrite.js:3:26)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at Object.cookieSession [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js:113:5)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at Object.cookieParser [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at resume (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/static.js:60:7)
at SendStream.error (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/static.js:73:37)
at SendStream.EventEmitter.emit (events.js:126:20)
at SendStream.error (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/send/lib/send.js:147:51)
You could rewrite the URL before you get to the handler you want to use.
app.use(function(req, res, next) {
if (req.url === '/toto') {
req.url = '/heytoto';
}
next();
});
app.get('/heytoto', ...);
I've used a similar method to do URL rewrites with regular expressions.
So I had sort of the same issue. I wrote an app that uses the history API on browsers and I wanted to rewrite all non-static URLs back to index.html. So for static files I did:
app.configure(function() {
app.use('/', express.static(__dirname + '/'));
});
But then for the history API generated paths I did:
app.get('*', function(request, response, next) {
response.sendfile(__dirname + '/index.html');
});
This meant that any request that wasn't a file or directory in / (such as a URL generated by the history API) wouldn't be rewritten or redirected but instead the index.html file will be served and that then does all the JS routing magic.
Hopefully that's close to what you're looking for?
A solution that works without response.sendfile(..) is to use a rewrite middleware that is inserted prior to app.use(express.static(..)) like this:
// forward all requests to /s/* to /index.html
app.use(function(req, res, next) {
if (/\/s\/[^\/]+/.test(req.url)) {
req.url = '/index.html';
}
next();
});
// insert express.static(...)
This way, expressjs properly recognizes the rewrite. The static middleware will then take care of serving the file.
1) Your rewrite middleware must appear before the middleware/function that will handle the request.
Won't work:
app.use('/hello', () => sayHello() );
app.use(() => rewriteURLToHello()); //it's too late to try to rewrite a URL to /hello
Will work:
app.use(() => rewriteURLToHello()); //we can rewrite a URL to /hello
app.use('/hello', () => sayHello() ); //rewritten URL will be handled here
2) Your middleware must not be bound to the path you're trying to rewrite
Won't work:
app.use('/hello', (req, res, next) => {
//'/hello' has been trimmed from req.url
//req.url is / if the request was for /hello
req.url = '/goodbye'; //technically setting full path to /hello/goodbye
next(); //will only call other middleware in the /hello chain
});
app.use('/goodbye', () => sayBye()); //won't work
Will work:
app.use((req, res, next) => { //runs for every path. Same as .use('/',
//'/hello' has NOT been trimmed from req.url
//req.url is /hello if the request was for /hello
if (req.url.startsWith('/hello')) {
req.url = '/goodbye'; //full path now /goodbye
}
next(); //will continue calling all middleware
});
app.use('/goodbye', () => sayBye()); //will work
you could check the url with an if condition and use app.redirect to redirect to a certain url.
Try this:
app.get('/toto', function(req, res) {
res.redirect('/heytoto');
});

download don't provide client download file [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());
}
});
}

Breaking out express routes into separate files

I have tried every answer I've found on s/o, and I'm sure I must be missing something. What doesn't error on me instead gives me a 404. I tried answers from Organize routes in Node.js, strongloop's route-separation pattern, the answers from How to include route handlers in multiple files in Express?, hit similar errors as in Router.use requires middleware function? but none of those answers worked, either. The answer for Unable to Split Routes into Separate Files in Express 4.0 doesn't error, but also 404s. It seems like each answer has a different syntax and style, and maybe it's that I'm mixing and matching incorrectly?
Right now my /routes/persons.js has this pattern:
var express = require('express');
var persons = express.Router();
persons.route('/persons/:user_id')
.put(function (req, res, next) {
// etc
});
module.exports = persons;
In my server.js file, I've got:
var persons = require('./routes/persons');
app.use('/persons', persons);
This combination doesn't throw errors, but it also doesn't do anything. I've tried adding the endpoint to server.js lines:
var persons = require('./routes/persons');
app.get('/persons/:user_id', persons.addpersons);
and stripping persons.js down to just export functions:
exports.addpersons = function (req, res, next) {
var list = req.body;
// etc
}
Plus variations like wrapping the whole person.js file in module.exports = function(), sticking module.exports = router at the end, using app instead of router, etc.
What am I overlooking? Should I be adding some other middleware, rearranging how I call the endpoint, using app, or sticking with router.route? What are the most likely culprits when there's no error but the endpoint is still 404'ing?
many thanks in advance!
============= EDITED TO INCLUDE SERVER.JS =============
Since it's clear something is set wrong, somewhere, here's my server.js file:
var express = require('express');
var app = express();
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var router = express.Router();
var jwt = require('jsonwebtoken');
var config = require('./config');
var nodemailer = require('nodemailer');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var async = require('async');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email#gmail.com',
pass: 'password'
}
});
// I don't know if both are necessary, used multiple conflicting tutorials
app.use(require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
}));
app.set('superSecret', config.secret);
var Schema = mongoose.Schema,
Person = require('./models/person.js'),
User = require('./models/user.js'),
Event = require('./models/event.js');
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
// routes go here
app.use('/api', router);
app.listen(port);
console.log('gogogo port ' + port);
I have no idea where else I might look for why including routes requires such a break in the usual pattern. My config files? My procfile? Those are the only other files sitting on the server, not counting /models and /routes.
The key here is to understand what app.use() does to your req object (in particular to req.path), how app.get() and friends are different, and how Express wraps path-to-regexp (its internal path matching module) to handle routes.
1) app.use(path, middleware) mounts the middleware. Inside the mounted middleware/router, req.path is relative to the mount path. Only the beginning of the request path needs to match, so /foo will work for requests at /foo (relative path will be /), /foo/bar (relative path is /bar), etc.
app.use(function (req, res, next) {
console.log('Main: %s %s', req.method, req.path);
next();
});
app.use('/foo', function (req, res) {
console.log('In /foo: %s %s', req.method, req.path);
res.send('Got there');
});
Try running the setup above, navigate to localhost/foo and see the following logs:
Main: GET /foo
In /foo: GET /
2) app.get(path, middleware), app.post(path, middleware) etc. do not mount the target middlewares, so req.path is preserved. req.path must match the whole pattern you defined your route with, so /foo will only work for /foo requests.
app.use(function (req, res, next) {
console.log('Main: %s %s', req.method, req.path);
next();
});
app.get('/foo', function (req, res) {
console.log('In /foo: %s %s', req.method, req.path);
res.send('Got there');
});
Navigate to localhost/foo and see :
Main: GET /foo
In /foo: GET /foo
3) app.route(path), as explained in the Express docs, is just a convenience to define multiple app.get(middleware), app.post(middleware) etc. sharing the same path.
Now in your case, here is a working setup:
main
var persons = require('./routes/persons');
app.use('/persons', persons);
routes/persons.js
var router = require('express').Router();
router.route('/:user_id')
.post(function (req, res) {
// handle potato data
})
.get(function (req, res) {
// get and send potato data
});
module.exports = router;
This is convenient as you only have to set the /persons entry point once in your main file, so you can easily update it later on if needed (you could also import that path value from a config file, from your router object or whatever, Node is pretty flexible in this regard). The persons router itself takes care of its business controllers, regardless of where it is exactly mounted at.
I FIGURED IT OUT!
Of course, this might be the totally wrong way to go about it (pls tell me if so) but it WORKS.
in my server.js file, I have:
var persons = require('./routes/persons');
router.get('/persons/:user_id', persons);
router.post('/persons/:user_id', persons);
and my persons.js file now looks like this:
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Schema = mongoose.Schema,
Person = require('../models/person.js');
router.post('/persons/:user_id', function (req, res) {
var potatoBag = req.body;
Person.collection.insert(potatoBag, function onInsert(err, potatoBag) {
if (err) {
return res.json(err);
} else {
res.status(200).end();
}
});
});
router.get('/persons/:user_id', function(req, res) {
var id = req.params.user_id;
Person.find({'user_id':id},function(err, person) {
if (err)
return res.json(err);
res.send(person);
});
});
module.exports = router;
This seems like more overhead than most of the examples, but maybe it's because of a) using router.route and b) using imported schemas? I also had (req, res, next) in there, and it threw fits until I removed the next pieces. Probably still a bit awkward, but hey, it's working. Thanks for the help, everyone!
instead of
persons.route('/persons/:user_id')
.put(function (req, res, next) {
// etc
});
do:
persons.put('/persons/:user_id',function (req, res, next) {
// etc
});

How to set dynamic route for static files in express

Currently, to serve static files im doing something like this:
app.use('/', express.static(__dirname + '/public/'));
// then i start the server
http.createServer(app).listen(port, function() {
console.log('HTTP Express server listening on port %s', port);
});
However, this sets the same directory for that path for every request, under all conditions. What I want to do is something like this that varies the response request to request:
http.createServer(app).listen(port, function() {
if (someCondition) {
app.use('/', express.static(__dirname + '/public/'));
}
else {
app.use('/', express.static(__dirname + '/public/someotherpath'));
}
console.log('HTTP Express server listening on port %s', port);
});
How can I do this?
You do it the other way around you modify url to make your desire effect
app.use('/', function(req,res,next){
if(condition){
req.url = newURL // add something to lead to different directory
}
next();
});
app.use('/', express.static(__dirname + '/public/'));
// then i start the server
http.createServer(app).listen(port, function() {
console.log('HTTP Express server listening on port %s', port);
});
Old question...but this is a quick solution...
If you want to keep all the functionality that comes with express.static, then you can just monkey-patch req.url (since it's just middleware):
const path = require('path');
const express = require('express');
const app = express();
// Dynamic path, but only match asset at specific segment.
app.use('/website/:foo/:bar/:asset', (req, res, next) => {
req.url = req.params.asset;
express.static(__dirname + '/static')(req, res, next);
});
// Just the asset.
app.use('/website/*', (req, res, next) => {
req.url = path.basename(req.originalUrl);
express.static(__dirname + '/static')(req, res, next);
});
the result of express.static() is a middleware function, so you can call it dynamically with your condition.
app.get('/', (req, res, next) => {
if (condition) {
express.static(__dirname + '/public/')(req, res, next);
} else {
express.static(__dirname + '/public/someotherpath')(req, res, next);
}
});
I also had that same problem now i fixed it by making a condition just like the below code
app.use("/", (req, res, next) => {
//check a condition if its false then return
if(1 !== 1)return
//After returned all conditions
next()
}, express.static("public"))
And this code checks if 1 is not 1 then wont show the files if 1 is 1 then it shows all public files :)
Based on your last comment: you can still do this within the router
app.get('/somepath', function(req, res){
if(req.someCondition){
res.sendFile('./path/to/appropriate/file.html');
} else {
res.sendFile('./path/to/different/file.html');
}
}
Leave express.static to serve your common files like js, css, and images. Send different html files using the .sendFile() method. This avoids having to use the renderer if you prefer not to use something like jade or ejs

Download a file from NodeJS Server using Express

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());
}
});
}

Categories

Resources