Sorry, I'm new with NodeJS Express. I want to get all files from a folder. I tried the following but don't work, test is always empty string:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function(req, res, next) {
var test = '';
const testFolder = './public/images';
fs.readdir(testFolder, (err, files) => {
test = files[0];
})
res.render('index', { title: 'Express', file: test });
});
Basically, I want to get all filenames from public images folder.
Problem here is res.render() will be executed before test is assigned to files[0], because the fs.readdir is asynchronous process. Before your callback is called res.render is excuted. And also, if you are trying to get all files from the folder you should pass files array. Please take a look at this for more info. You might wanna try the below code.
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function(req, res, next) {
var test = '';
const testFolder = './public/images';
fs.readdir(testFolder, (err, files) => {
// test = files[0]; this will assign test to the first element of the array of file
test = files;
res.render('index', { title: 'Express', file: test });
})
});
Related
I'm trying to read a video file, given the file name as a request parameter to express router endpoint. However, only the console.log ging of params happens and I can never see video file data logged into the console. What am I doing wrong here? Any helpful tip is highly appreciated.
var express = require("express");
var fs = require('fs')
var path = require('path')
var router = express.Router();
router.get("/:file", (req, res) => {
console.log(req.params.file)
fs.readFileSync(path.resolve('/uploads', './'+req.params.file), function (err, data){
if (!err) {
console.log("d: ",data);
res.send(data)
} else {
console.log(err);
}
});
});
You don't need to provide a callback to fs.readFileSync, it will return the data once it has completed.
Be aware, it the file size is large, this will block the main thread and would not be considered good practice.
You'd use it like so:
var express = require("express");
var fs = require('fs')
var path = require('path')
var router = express.Router();
router.get("/:file", (req, res) => {
try {
console.log(req.params.file)
let data = fs.readFileSync(path.resolve('/uploads', './'+req.params.file));
console.log("d: ",data);
res.send(data)
} catch (err) {
console.error(err);
res.status(500).send("Something bad happened");
}
});
If you wish to do this asynchronously using fs.readFile, I would modify your code like so:
var express = require("express");
var fs = require('fs')
var path = require('path')
var router = express.Router();
router.get("/:file", (req, res) => {
console.log(req.params.file)
fs.readFile(path.resolve('/uploads', './'+req.params.file), function (err, data){
if (!err) {
console.log("d: ",data);
res.send(data)
} else {
console.log(err);
}
});
});
I am sending json by POST to nodejs, I declared router.post in index.js, (/routes)
How I can save it so I can actually use that later on? Keep in mind that every 60sec I am getting new data that should replace the old one.
I am listening on port 3000
var express = require('express');
var router = express.Router();
var saveme
/* GET home page. */
router.get('/index', function(req, res, next) {
res.render('index', { title: 'RLH' });
});
router.post('/index', function(req, res, next) {
data = req.body;
console.log('OK')
});
module.exports = router;
I don't know how can I save what I get trough POST, so later on I can use it on my website.
There are multiple ways to use Global variable:
Method1
Using app.locals :
declare app.locals.data = {}; in main file (ex:server.js)
var app = express();
app.locals.data = {};
app.locals available to req object as req.app.locals. When you have new data you can update it as :
req.app.locals.data = req.body;
Method2
Using global object
Assign new data as global.data = req.body
You can always access data as global.data in same or different module
Method3(Recommended)
Create file globaldata.js with below code
module.exports = {};
Import globaldata.js where you need to access or update global data as
var globaldata = require('./globaldata.js');
globaldata = req.body;
What is recommended? global method for small apps, module.exports for big apps.
You can read below ref. for more details:
https://www.hacksparrow.com/nodejs/global-variables-in-node-js.html
http://expressjs.com/en/api.html#app.locals
If by saving the data you mean storing it in a variable you can do:
var express = require('express');
var router = express.Router();
var saveme;
/* GET home page. */
router.get('/index', function(req, res, next) {
if (saveme) {
// you can use `saveme`
res.render('index' + saveme.toString(), { title: 'RLH' });
}
else {
res.render('index', { title: 'RLH' });
}
});
router.post('/index', function(req, res, next) {
data = req.body;
// set `saveme`
saveme = data;
});
module.exports = router;
I can upload a file via postman and download a file from server in two different service .. But what i need is ..In a single call i should able to upload the file to server ,then perform some operation after performing some operation i should able to download the file automatically.
Here is my code.
My firsts service(file upload operation)
var express = require('express');
var fs = require('fs');
var formidable = require('formidable');
var router = express.Router();
/* GET home page. */
router.post('/', function(req, res, next) {
var form = new formidable.IncomingForm();
form.uploadDir="./file"
form.keepExtensions=true;
form.maxFileSize=10*1024*1024;
form.multiples=false;
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
});
module.exports = router;
Download service
var express = require('express');
var router = express.Router();
var express = require('express');
router.get('/', function(req, res, next) {
var file = './file/myOutput.txt';
var name = 'ENC.txt'
res.download(file, name);
});
module.exports = router;
Now i need to make this two service as one?
var express = require('express');
var formidable = require('formidable');
var app=express();
async function calculation(parameters)
{
if(parameters)
{
//Here you can do calculation depending upon parameter values
}
else
{
//Display error or as per your choice
}
}
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
});
async function cal(res,file,form)
{
try{
const data = await calculation(true)
if(data){
res.set({
'Location' : __dirname+'/index.html',
});
res.download( __dirname+file.name);
}
}
catch(error)
{
console.log(error);
}
}
app.post('/',function (req,res){
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin',function(name,file){
file.path = __dirname+file.name;
console.log("Uploading");
});
form.on('file',
function(name,file)
{
console.log('Uploaded ',file.name);
cal(res,file);
});
});
Hope it helps
I'm building a node.js+express application in which the user will input some data, the generates a PDF with pdfkit and the file is sent to the user. I'm being able to generate the file successfully, the problem is that when I download the file generated, it's empty. I can't even open the PDF, the reader (Preview, native reader in macOS) says that the file is empty. I'm using the following code:
var express = require('express');
var router = express.Router();
var guid = require('guid');
var PDFDocument = require('pdfkit');
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/criar', function(req, res, next) {
var filename = guid.raw()+'.pdf';
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream(filename));
doc.font('fonts/UbuntuMono-R.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
doc.end();
res.download(filename, 'rifas.pdf', function(err){
if(!err){
fs.unlink(filename);
}
})
});
module.exports = router;
Do you have any idea on why my downloaded files are empty, while in the server they're being generated correctly?
Thanks!
Do you really need the physical file? If not then you can stream directly to the client:
var express = require('express');
var router = express.Router();
var PDFDocument = require('pdfkit');
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/criar', function(req, res, next) {
var doc = new PDFDocument();
doc.pipe(res);
doc.font('fonts/UbuntuMono-R.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
doc.end();
});
module.exports = router;
If you need both the physical file and a download response (like I do), you can wait for the close event of the stream:
let stream = fs.createWriteStream(filename);
doc.pipe(stream);
// Do whatever you need with doc
doc.end();
stream.on("close", () => {
res.download(filename, 'rifas.pdf', function(err){
if(!err){
fs.unlink(filename);
}
})
});
This is my code:
<script type="text/javascript">
const express = require('express'),
router = express.Router();
var hosSchemaModel = require('../schema.js')
var path = require("path")
// const app = express()
var port = process.env.PORT || 8080;
router.listen(port);
router.get('/requests/:_id', (req, res, next) => {
console.log('Dynamic Link WORKS!!');
hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){
res.json(request)
// res.sendFile(path.join(__dirname+'../homePage.html'))
});
});
router.get('/all', (req, res) => {
console.log('Dynamic Link WORKS!!');
res.send('WORKS!!');
// hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){
// res.json(request)
// res.sendFile(path.join(__dirname+'../homePage.html'))
// });
});
module.exports = router;
</script>
I tried to put it in the main process as well but it didn't work and I figured it should be implemented in the client-side. The routers doesn't work.
when I use <a href="/all" it takes me to an empty page and nothing is printed to the console
What am I doing wrong here?
This code is Node related and should be in a separated file. Let's call it server.js.
It should also load your static files and become your main server.
Then in the electron main.js file, you should require your express server and load:
const server = require('./server');
...
mainWindow.loadUrl('http://localhost:5000')
Complete example here: https://gist.github.com/maximilian-ruppert/a446a7ee87838a62099d