How to use Express.js and http.createServer function in Node.js - javascript

I have the following Node.js code:
var app, fs, express
fs = require("fs")
app = require("http").createServer(function (req, res) {
var file
file = req.url === "/" ? "/index.html" : req.url
console.log(req.method + " " + file)
return fs.readFile("./views" + file, function (err, data) {
if (err != null) {
res.write(404)
return res.end("<h1>HTTP 404 - Not Found</h1>")
}
res.writeHead(200)
return res.end(data)
})
})
app.listen(3000, function () {
return console.log("running...")
})
I need to include Express.js in my application, for example:
app = express()
express = require("express")
app.use(express.bodyParser())
app.use(app.router)
app.get("/form", function (req, res) {
res.sendfile("./form.html")
})
http.createServer(app).listen(3000)
How to combine those two snippets?

By joining 2 code in one , i guess you want to use the middleware you described in 1st file
var app = express();
var express = require("express");
app.use(express.bodyParser());
app.use(app.router);
app.get("/form", function (req,res){
res.sendfile("./form.html");
});
app.use(function(req, res) {
var file;
file = req.url === '/' ? '/index.html' : req.url;
console.log(req.method + " " + file);
return fs.readFile("./views" + file, function(err, data) {
if (err != null) {
res.write(404);
return res.end("<h1>HTTP 404 - Not Found</h1>");
}
res.writeHead(200);
return res.end(data);
})
http.createServer(app).listen(3000);

// Create app with Express
let app = express();
// Create a Node server for Express app
let server = http.createServer(app);
// Parse application/json
app.use(bodyParser.json());
// Parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/form", function (req,res){
res.sendfile("./form.html");
});
app.use(function(req, res) {
var file;
file = req.url === '/' ? '/index.html' : req.url;
console.log(req.method + " " + file);
return fs.readFile("./views" + file, function(err, data) {
if (err != null) {
res.send(404);
}
res.json(data);
})
server.listen(3000);

Related

Edit and create HTML content using node.js

I want to create html content that looks something like this using node.js.
<div class="outputs">
...
</div>
I have the following code:
var mongoose = require("mongoose");
var express = require("express");
var bodyParser = require("body-parser");
var Url = require("./models/Url");
var shortId = require("shortid");
var http = require("http");
var app = express();
var { JSDOM } = jsdom;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MLAB_URI);
app.get("/urls", (req, res, next) => {
Url.find({}, function(err, data) {
res.json(data);
console.log(data.length);
});
});
app.get("/deletebase", (req, res, next) => {
Url.deleteMany({}, function(err, data) {
res.json(data);
});
});
app.use(express.static(__dirname + "/"));
app.get("/:shortUrl", function(req, res, next) {
Url.findOne({ shortUrl: req.params.shortUrl }, function(err, findUrl) {
if (err) console.log(err);
if (!findUrl) {
return next({ status: 400, message: "unknown shorturl" });
}
res.redirect(findUrl.longUrl);
});
});
app.post("/", function(req, res) {
var url = new Url(req.body);
var hostname = req.headers.host;
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
var regex = expression;
if (regex.test(url) === true) {
url.shortUrl = shortId.generate();
url.fullUrl = "https://" + hostname + "/" + url.shortUrl;
url.save(function(err, savedUrl) {
if (err) console.log(err);
res.redirect("https://" + hostname);
});
} else {
res.redirect("https://" + hostname);
}
});
var options = {
runScripts: "dangerously",
resources: "usable"
};
app.listen(3000, function() {
console.log("RUNNING");
});
I want to get length of the data and create that many div objects with longUrl and shortUrl objects in it. Also when database will be updated new div object should be created, and when I delete database information all the div elements should be deleted too, is this possible to do?
You should be using a templating engine for this the two most popular ones for Node.js are pug(formerly Jade) and hbs(Handlebars.js).
There are a lot of other template engines here you could consider.

Node JS Separate a function from a route

I created some code (a simple file uploader) that works well all on one file. I would like to start breaking up the code into several files. I would like to have a routes.js (to control the routes), imports.js (that contains my function) and my server. I am having problems calling my imports from the route. I am getting error imports is not a function. Thank you!!
Server.js -----------------------------------------------------------
var express = require('express');
var app = express();
var passport = require('passport');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var imports = require('./src/import.js');
var port = process.env.PORT || 8080;
app.use(express.static('public'));
require('./src/import')(imports);
require('./app/routes.js')(app, imports);
app.listen(port);
console.log('The app is running on port ' + port)
routes.js-----------------------------------------------------------
module.exports = function (app, imports) {
//home Page
app.get('/', function (req, res) {
res.render('index.ejs');
});
app.post('/import', imports(){});
};
import.js---------------------------------------------
var multer = require('multer');
var fs = require('fs');
module.exports = function (imports) {
var imports = multer({ dest: 'C:/Users/ron/temp/' });
var type = imports.single('file');
imports( type, function (req, res) {//removed type
var fileType = req.file.type;
console.log('output' + req.file);
console.log(fileType);
var file = __dirname + "/" + req.file.name;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log(err);
} else {
var fileName = req.file.originalname;
response = {
message: 'File uploaded successfully',
fileinfo: req.file,
filename: fileName
};
}
console.log(response);
res.end(JSON.stringify(response));
var filePath = req.file.destination + req.file.originalname;
fs.rename(req.file.destination + req.file.filename, req.file.destination + req.file.originalname, function (err) {
if (err) console.log('ERROR:' + err);
console.log('the path is...' + filePath);
console.log('the name is...' + fileName);
});
});
});
});
};
Single file solution..................................................
var express = require('express');
var app = express();
var passport = require('passport');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var multer = require('multer');
var fs = require('fs');
var port = process.env.PORT || 8080;
var imports = multer({ dest: 'C:/Users/ron/temp/' });
var type = imports.single('file');
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render('index.ejs');
});
app.post('/import', type, function (req, res) {//removed type
var fileType = req.file.type;
console.log('output' + req.file);
console.log(fileType);
var file = __dirname + "/" + req.file.name;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log(err);
} else {
var fileName = req.file.originalname;
response = {
message: 'File uploaded successfully',
fileinfo: req.file,
filename: fileName
};
}
console.log(response);
res.end(JSON.stringify(response));
var filePath = req.file.destination + req.file.originalname;
fs.rename(req.file.destination + req.file.filename, req.file.destination + req.file.originalname, function (err) {
if (err) console.log('ERROR:' + err);
console.log('the path is...' + filePath);
console.log('the name is...' + fileName);
});
});
});
});
app.listen(port);
console.log('The app is running on port ' + port)
Note that every function you include in your router must have reqest and response object as a parameter.
Change your function as :
function imports (req,res){
//your code
}
module.exports ={
imports:imports
}
And now import this function in router file.

type error: app.use() requires middleware

I can not figure out why I get this error.
When I try to run node filename.js, I got a type error on the console:
app.use() requires middleware functions
I expect the result is:
Working on port 3000
Below is my code:
var express = require('express');
var multer = require('multer');
var fs = require('fs');
var app = express();
var DIR = './uploads/';
var upload = multer({dest: DIR});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://valor-software.github.io');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(multer({
dest: DIR,
rename: function (fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
}
}));
app.get('/api', function (req, res) {
res.end('file catcher example');
});
app.post('/api', function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end(err.toString());
}
res.end('File is uploaded');
});
});
var PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log('Working on port ' + PORT);
});
According to the document of multer on npm. You can not pass multer object as an argument directly. You should pass them by calling member functions, such as single(), field(), array().
For example:
upload = multer({
dest: DIR,
rename: function (fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
}
})
app.use(upload.single(...));
app.use(upload.array(...));
app.use(upload.fields(...));
app.use(upload.any());

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

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