how to send compressed file with nodejs - node.js

I made the following code to send .zip file upon get request to localhost:3000 but the file is being download without filename and without extension
const express = require("express");
const app = express();
app.get("/", async (req, res) => {
res.sendFile("/files/a.rar", {
extensions:["rar", "zip"]
})
})
app.listen(3000, () => {
console.log("server connected");
});
how i can do this

Have you tried using res.download(...) instead of res.sendFile(...)?
I had the same issue and I was able to make it work by using this code block.
import path from 'path';
...
app.get("/", async (req, res) => {
res.download(path.resolve('files/a.rar'), {
extensions: ["rar", "zip"],
});
});
Give it a try!

Related

Node.js not showing page properly

I watched a Youtube video & copied the code from it but my page is not loading properly, It looks like this-
Node.js code -
import express from "express";
import bcrypt from "bcrypt";
//init server
const app = express();
//middlewares
app.use(express.static("public"));
app.use(express.json())//enables from sharing
//routes
//home route
app.get('/', (req, res) => {
res.sendFile("index.html", {root : "public"})
})
// 404 route
app.get('/404', (req, res) => {
res.sendFile("404.html", {root : "public"})
})
app.use((req, res) => {
res.redirect('/404')
})
app.listen(3000, () => {
console.log('listening on port 3000');
})
You are using a file: path inside of your HTML code (or other public files) which isn't possible as you aren't reading from a filesystem, you are using HTTP. Use proper paths instead in your links.

localhost infinitely loading nodejs

I am starting to learn Node.js and as the first step I am deploying my server using node.js
This is my code:
const express = require("express");
const { readFile } = require("fs/promises");
const app = express();
app.get('/', (request, response) => {
readFile('./home.html', 'utf8', (err, html) => {
if(err){
response.status(500).send("Sorry, we are out of order");
}
response.send(html);
})
})
app.listen(3000, () => console.log(`App available on http://localhost:3000`))
But the when i click that link, the localhost seems to be loading infintely.I have tried with different ports.I am using powershell for this and not a WSL.What seems to be the problem here?
Try to use node path module, and put your html file into root directory. It works like a charm.
const express = require("express");
const path = require("path");
// const { readFile } = require("fs/promises");
const app = express();
// app.get("/", (request, response) => {
// readFile("./home.html", "utf8", (err, html) => {
// if (!err) {
// response.status(500).send("Sorry, we are out of order");
// }
// response.send(html);
// });
// });
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/home.html"));
});
app.listen(3000, () => console.log(`App available on http://localhost:3000`));

How to use Node to read PUT file?

I'm trying to replicate the functionality of bashupload.com but using node. I want the simplicity of just doing curl host -T file but I ran into some problems because I can't seem to understand how to read the PUT file. Curl uses a PUT request when you use the -T option, so it has to be PUT.
I tried using packages like multiparty:
receiveAndUploadFile: function (req, res) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
// var fs = require('fs');
form.parse(req, function(err, fields, files) {
console.log('The files', files)
console.log('The fields', fields)
})
res.send("Okay, bye.")
}
But this prints undefined values for files and fields.
I also tried using express-fileupload middleware
app.use(fileUpload({}));
but still, if I try to print req.files then I will get undefined.
Is there any specific way to read the file?
Thanks a lot!
This is my main file, index.js::
const express = require("express");
const path = require("path");
const app = express();
const port = 8080;
const tools = require("./tools");
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.use(express.static(__dirname + "/assets"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.get("/f", (req, res) => {
res.send("This route is only available as a POST route.");
});
app.put("/f", tools.receiveAndUploadFile);
app.listen(port, () => {
console.log(`Server started listening on port: ${port}`);
});
And the tools.js file:
const fs = require("fs");
const path = require("path");
module.exports = {
receiveAndUploadFile: function (req, res) {
console.log("Files: ", req.files);
res.send("Okay bye");
},
};
This is printing "Files: undefined" to the console.
A PUT and a POST are effectively the same thing. To upload arbitrary data, just read the data stream and write it to a file. Node provides a .pipe method on streams to easily pipe data from one stream into another, for example a file stream here:
const fs = require('fs')
const express = require('express')
const app = express()
const PORT = 8080
app.get('/*', (req, res) => res.status(401).send(req.url + ': This route is only available as a POST route'))
app.put('/*', function (req, res, next) {
console.log('Now uploading', req.url, ': ', req.get('content-length'), 'bytes')
req.pipe(fs.createWriteStream(__dirname + req.url))
req.on('end', function () { // Done reading!
res.sendStatus(200)
console.log('Uploaded!')
next()
})
})
app.listen(8080, () => console.log('Started on :8080'))
If you do a PUT to /file.mp4, it will upload all the data over to the script dir (__dirname) + the URL file path.
via curl, curl http://localhost:8080/ -T hello.txt

Expressjs server and external api calls

I'm new to frontend development and express server. When I tried to start an express.js server with react (with axios calls to external apis), it seems express.js is adding 'localhost:3000' in front of the external API calls so they fail.
In my server.js:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '.', 'dist');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server is up!');
});
Which leads to the API call to www.example.com/api/ to become http://localhost:3000/www.example.com/api/
I also tried to filter the req by writing:
app.get('*', (req, res) => {
if (req.url.match(/\/api\//) === null) {
res.sendFile(path.join(publicPath, 'index.html'));
}
});
But it does not change things...
Can anyone help out this newbie that is me?
Update1 Adding the code for calling the api:
This is the api call:
const getSomething = () => {
try {
const url = endpoints.GET_SOMETHING;
return axios.get(url);
} catch (err) {
console.log(err);
}
};
endpoints.GET_SOMETHING is the api URL: www.example.com/api/getSomething
You need to put a / in the url
app.get('/*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
and also your endpoint url should start with https://, http:// or //

App.js to redirect to a module

I am debugging into a NODE JS application and I am very new to node js. I have a REST module file
students.js
module.exports = function (service) {
/**
* Retrives data from DB
*/
service.get('/mobile/students', function (req, res) {
res.set('Content-Type', 'application/json')
.status(200)
.json(DBHelper.getAllStudents());
});
service.post('/mobile/students', function (req, res) {
res.status(200).json(data);
});
});
To run it locally I am using the following app.js
const express = require('express');
const app = express();
var routes = require('./students');
app.get('/', function (req, res) {
res.send('Hello World!')
});
app.listen(3010, function () {
console.log('Example app listening on port 3010!')
});
When I hit
http://localhost:3010/students, I am hitting a 404.
How do I explicit route the path to the student modules?
you need to add routes(app); line after var routes = require('./students'); then Your routes will be mounted..
http://localhost:3010/students if use this it will prompt you again with 404 but if you use http://localhost:3010/mobile/students it will produce desire output..

Resources