I'm looking for a way to request a csv file from any url to save it then. If possible only using fs, http, request and express modules.
For testing I tried it with
request('http://localhost:3000/data1.csv').pipe(fs.createWriteStream('data2.csv'))
but i always get as a resonse (data2.csv)
<pre>Cannot GET /data1.csv</pre>
Simplified Code
const fs = require('fs')
const request = require('request')
const express = require('express')
const app = express()
app.listen(3000)
app.get('/download', (req, res) => {
request('http://localhost:3000/data1.csv').pipe(fs.createWriteStream('data2.csv'))
})
The file data1.csv is saved in the root of my project folder. But is this also the root of my nodejs server from where I started it?
What I'm doing wrong here?
Thanks!
You need to have an explicit handler that returns data1.csv:
app.get('/data1.csv', (req, res) => {
res.sendFile('data1.csv');
});
Related
I use a REST client to test my app (Insomnia and postman). My app literally does nothing:
const express = require('express');
const app = express();
const fileUpload = require('express-fileupload');
app.use(express.json())
app.use(fileUpload());
app.post('/', fileUpload(), function(req, res) {
console.log(req.files)
res.send('a')
});
const PORT = 9999;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
Whenever I try to upload a file to this service req.files is undefined. I took this code from express docs page and from a few stackoverflow questions and it just doesn't work for me. Content-length is good (40k seems right)
Content-type is auto set by my REST client. Do I have to change this?
I tried simply printing whole request object and body is empty and files is not even present there
So for anyone wondering. fileupload requires form-data Content-type. Moreover, it also requires a file to have a "key" within this form-data. It's a shame documentation fails to mention this.
Just do one thing: remove file fileUpload() from post endpoint and check, find below code for your reference.
app.post('/', function(req, res) {
console.log(req.files)
res.send('a')
});
function skipBR() {
location.href = 'boardroom.ejs';
}
here I want to call boardroom.ejs file in different page using function.
The location.href = '/path' is a client side function, in server side is used the Express function res.redirect('/path') as #santhosh has mentioned in the comments.
This would look something like:
terminal:
npm install -s express
your .js file:
const express = require('express');
const app = express();
app.get('/', (req, res) =>
res.redirect('/boardroom.ejs');
});
I would like send send file from postman to the server, and then send this file to sharepoint using REST API.
When I send my file form-data format body from postman to the server I don't know how to recover it
When I do console.log(file) on server side I have nothing
Can you put your code of the nodeJS server? Without your used code part it is hard to give an answer but you can simply catch the post request as below.
You should use body-parser to receive your data.
run npm install body-parser
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.post('/test', (req, res) => {
console.log(req.body.file)
}
app.listen(5000,()=>{
console.log("Running on port: "+5000)
})
Its working using multer
const multer = require('multer')
I was wondering if you can call create a GET request on a RESTApi server to download a file. For example if i called a GET request to http://<IP>/storage/download/:filePath/ it would download that file. I am writing the RESTAPi in nodejs.
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const root = {}
//for this example say filepath = api%2Fstorage%2FImages%2FtestPhoto.png or api/storage/Images/testPhoto.png
router.get("/download/:filePath", (req, res, next) => {
var filePath = req.params.filePath;
filePath = decodeURIComponent(filePath)
res.sendFile(filePath);
// this is what im questioning. If i use this will it send the file? if so how will i download it on the front end?
})
Yes. If the server directory is this
main.js
└── storage
└── Image
└── testPhoto.png
Add this,
router.use('/api/storage', express.static('storage'));
Then request it from frontend. GET /api/storage/Image/testPhoto.png
Express has a helper for this to make life easier.
app.get('/download', function(req, res){
const file = `${__dirname}/folder/download.csv`;
res.download(file); // Set disposition and send it.
});
here is my code
var express=require("express");
var app=express();
var port=8181;
app.use(express.static(__dirname));
app.listen(port);
it is serving static file properly
I want to log when a file with an extension .xls is being requested
how can i achieve it ?
The path core module gives you the tools to deal with this. So, just put this logic in a middleware before your static middleware, like:
var express = require("express");
var path = require("path");
var app = express();
var port = 8181;
app.use(function (req, res, next) {
var filename = path.basename(req.url);
var extension = path.extname(filename);
if (extension === '.css')
console.log("The file " + filename + " was requested.");
next();
});
app.use(express.static(__dirname));
app.listen(port);
You want to log what serve-static (express.static) gives in response. There're several ways to do this.
Method Ⅰ A middleware for manual checks.
You may put (app.use) a middleware that logs a request if it's for express.static, before express.static. Rodrigo Medeiros' answer does this. But this way, you have to rewrite the code for checks when the options for the serve-static middleware changes, which might be a maintaining issue.
Method Ⅱ Hooking into express.static; leaking info out of it.
Well, express.static knows what files it gives best. It just, unfortunately, does not let us know and log it. But there's a hack for this: the setHeaders option, which is a callback function supposedly used to set custom response headers. It's called when express.static makes a response and gets enough information to log what you want to.
const express = require("express");
const path = require("path");
const app = express();
const asset_dir_path = "assets/";
app.use(express.static(asset_dir_path, {
index: false,
setHeaders: (response, file_path, file_stats) => {
// This function is called when “serve-static” makes a response.
// Note that `file_path` is an absolute path.
// Logging work
const relative_path = path.join(asset_dir_path, path.relative(asset_dir_path, file_path));
console.info(`#${Date.now()}`, "GAVE\t\t", relative_path);
}
}));
Just do
var express=require("express");
var app=express();
var port=8181;
app.use(function(req, res, next) {
// check for .xls extension
console.log(req.originalUrl);
next();
}, express.static(__dirname));
app.listen(port);