download JSON file in node Js - node.js

I am creating a json file, but not sure how to download it.
here is my code
let jsonExport= directory path;
exportTemp (name, title, id) {
let obj = new Array() ;
obj.push({Title: name, Prefix:title, UserId:id });
let file_name= jsonExport + name + ".json"
fs.writeFile(file_name, JSON.stringify(obj, null, 4), (err, response) => {
if (err) {
console.error(err);
return;
};
console.log("File has been created");
});
return (file_name);
};

If you're using express, you can simply do it like this
res.download(file_name);
or without express
app.get('/downloadFile/', (req, res) => {
var files = fs.createReadStream(file_name);
res.writeHead(200, {'Content-disposition': 'attachment; filename=demo.pdf'});
files.pipe(res)
})

Related

multiple file upload not working with formidable in node js

app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
try{
if (files.file.name != '') {
file_newname = dt.MD5(files.file.name + Date() + Math.random()) + '.jpg' + ;
var file_newpath = './tmp/' + file_newname;
fs.readFile(file_oldpath, function (err, data) {
// Write the file
fs.writeFile(file_newpath, data, function (err) {
console.log('File written!');
res.end(JSON.stringify({
message: 'file uploaded successfully'
}));
});
});
}
}catch (e) {
}
});
});
The single image upload is working perfectly.I tried the following code
var form = new formidable.IncomingForm();
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);
But only a single image gets uploaded. i m using react in frontend. Node and express in backend.
I also tried multer. But that doesnt working
app.post('/getrast', upload.array('files'), function (req, res) {
res.json({data: req.files});
});
Use the multiple flag with the incoming form with true as value.
var form = new formidable.IncomingForm();
form.multiples = true; //use this while dealing with multiple files
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
fs.rename('add your logic here for renaming files'); // rename it here
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);

Writing json back but assigned as a variable

I have the following node code which successfully writes as a json object:
const writeFile = (fileData, callback, filePath = dataPath, encoding = 'utf8') => {
fs.writeFile(filePath, fileData, encoding, (err) => {
if (err) {
throw err;
}
callback();
});
};
/* adds a new customer to the list */
router.post('/', async (req, res, next) =>
{
readFile(data => {
// add the new user
data = req.body;
writeFile(JSON.stringify(data, null, 2), () => {
res.status(200).send('whole content updated');
});
},
true);
});
This works fine if I want to write back as properly formatted json, ie
{"example": "hello"}.
However due to various reasons I want to write the following back:
var systemCode = {"example": "hello"}
How would I go about changing the node code to reflect this? Just to clarify, I'm writing this back as a physical .js file.
You can build the string you wish to write in the post handler, then write this to the file.
For example:
/* adds a new customer to the list */
router.post('/user', async (req, res, next) =>
{
readFile(data => {
// add the new user
data = req.body;
const fileContents = "var systemCode = " + JSON.stringify(data, null, 2);
writeFile(fileContents, () => {
res.status(200).send('whole content updated');
});
}, true);
});

How to download the pdf file after generated in nodejs

I'm building a web application in Node.js 10.x and angular 6.x. I wish to generate a PDF and download it via browser.
angular 6.x
generatePDF(params): any {
return this.http.post(this.url('generatePDF'), params, this.getRequestOptions())
.pipe(map((res: any) => {
return res;
})
);
}
Node.js
async generatePDF(options = { format:'A4' }) {
return new Promise((resolve, reject) => { ejs.renderFile(this.templateName, this.data, (err, res) => {
if (err) {
return reject(err);
}
pdf.create(res, options)
.toFile(this.fileName, (err, res) => {
if (err) {
return reject(err);
}
resolve(res);
});
});
});
}
I have solved this problem as follows.
Node.js
let pdffilename = username + '_' + gameName.replace(/ /g, "_") + '.pdf';
pdfReport = new Report(gameName, ejsfilename, pdffilename, refined_score);
await pdfReport.generatePDF();
res.sendFile(pdfReport.fileName);
After Creation of PDF path , you can use the following code to download your file
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
res.header('content-type', 'application/pdf');
res.download(PDF_PATH, PDF_NAME + '.pdf');

Download file from server (Nodejs Express > React)

how can i send a file(docx) to a user ?
this is my server code :
app.get('/api/topic/file/:id', function (req, res, next) {
Topic.findByIdAndUpdate(req.params.id)
.exec()
.then((topic) => {
let filepath = topic.news_file[0]
console.log('filepath', filepath)
res.download(filepath, topic.name + '.docx', function (err) {
if (err) {
console.log('api get file err ', err);
} else {
// decrement a download credit, etc.
}
});
}).catch((err) => console.log('error', err));
})
this does not trigger a download on the browser.
i am using react as front-end.
on the client i have a button triggering this upon click :
handleDownload() {
if (this.state.lastClicked) {
fetch("/api/topic/file/" + this.state.lastClicked._id)
.then(results => {
console.log('results', results)
return results;
})
} else {
//somthings...
}
}
Found a solution using downloadjs..
var download = require("downloadjs")
async handleDownload() {
const res = await fetch("/api/topic/file/" + this.state.lastClicked._id);
const blob = res.blob();
download(blob, this.state.lastClicked.name + '.docx');
}

TypeError: res.json is not a function when using require('fs');

Trying to pass contents for files I am reading via res.json. I think I am over writing my res function, but I dont see a fix.
app.get('/uploads/', (res, req) => {
dirname = './client/uploads'
fs.readdir(dirname, function(err, filenames) {
console.log(filenames)
if (err) {
console.log(err);
return;
}
filenames.forEach(function(filename) {
if (filename != '.DS_Store'){
fs.readFile(dirname + "/" + filename, 'utf-8', function(err, content) {
res.json({content: content})
if (err) {
//onError(err);
console.log(err)
return;
}
});
}
});
});
})
You mis-matched the arguments of /uploads route handler, req is the first argument
app.get('/uploads/', (req, res) => {
//...
})

Resources