Best way to save files node.js [duplicate] - node.js

This question already has answers here:
File uploading with Express 4.0: req.files undefined
(13 answers)
Closed 6 years ago.
I'm triying to upload an excel file with postman and save it in to a folder with node.js fs:
var file = req.body.file;
fs.writeFile("public/myExcelFile.xlsx", file, function(err) {
if(err) {
res.json(err);
} else {
res.json("The file was saved!");
}
});
But when I try to open the file after upload it is corrupt or empty,
can you tell me pls what im doing wrong?
In the future I have to upload another files like .docx or .csv so I want to know what is the best way to save these files, it's better save files in database(I´m using Sql server) as a blob ? or save the file in a folder and save the path in database?

You might want to try using node.js streams. I believe it's best to only save the path in the database.

Related

How to read and write xlxs and csv file using nodejs

first, I want to upload .xlxs and .csv file in node.js. then I want to read this file, edit this file, and also want to save this file in mongoose schema in the database.
and I am new in node.js and I want to learn node backend
please guide me, how I can do this and is this possible?
Reading and writing files in node uses the fs module. Its already included in core node so simply include it
const fs = require('fs')
// synchronous version that will wait until the whole file is read
let file_data = fs.readFileSync('/file/path/file.csv' , 'utf-8')
// async version
fs.readFile('/file/path/file.csv' , 'utf-8', (err, file_data) => {
if (err)
console.error(err)
else
console.info(file_data)
// file_data is your data as string
})
If you specifically need to read and edit csv/xlsx you'll need to browse NPM for packages that help out with that.
You can do it easily by using sheetjs
See this example : https://github.com/SheetJS/sheetjs/tree/master/demos/server

how to prompt where to download zip file created with archiver in node

I am trying to create a zip file in node using the code provided from how to create a zip file in node given multiple downloadable links, as shown below:
var fs = require('fs');
var archiver = require('archiver');
var output = fs.createWriteStream('./example.zip');
var archive = archiver('zip', {
gzip: true,
zlib: { level: 9 } // Sets the compression level.
});
archive.on('error', function(err) {
throw err;
});
// pipe archive data to the output file
archive.pipe(output);
// append files
archive.file('/path/to/file0.txt', {name: 'file0-or-change-this-whatever.txt'});
archive.file('/path/to/README.md', {name: 'foobar.md'});
//
archive.finalize();
When I use this suggestion, the zip file is downloaded without any kind of prompt asking me where I would like to save the file - is there any way I can make it so that a prompt is created asking me where I would like to save the file, which is quite normal these days?
If this is absolutely not possible, would it be possible to always save the file in the downloads folder (regardless of whether on mac or windows or any other operating system)?
So there's a couple of things here. In terms of a 'prompt' or 'pop-up' you won't find anything along the lines of WinForms out of the box, there are options for the command line such as prompts You can use that as your user input.
https://www.npmjs.com/package/prompts
You'll want to use path and more specifically path.join() to combat the mac/windows/linux issue.
Do you need to use path.join in node.js?
You can run an express server and create a route that uses res.download() in which you would provide the zipped file.
https://expressjs.com/en/api.html#res.download

How to save the ID of a saved file using GridFS?

I am trying to save the ID of the file that I send via GridFS to my MongoDB (working with Mongoose). However I cant seem to find out how to get the created ID in fs.files with code?
var writestream = gfs.createWriteStream({
filename: req.file.originalname
});
fs.createReadStream(req.file.path).pipe(writestream);
writestream.on('close', function (file) {
// do something with `file`
console.log(file.filename + 'Written To DB');
});
I cant seem to be able to save the ID of the File that I wrote via the writestream.
The file is created in the lists etc. but how do I manage to save the file so that I can save it in one of my other MongoDB Documents?
This is old and I think you already solved you problem.
If I correctly understood, you were trying to get the id of the saved file.
You can simply do this:
console.log(writestream.id);

How can I display files that have been saved as a Buffer?

I am saving files as Buffers in my mongo database (using mongoose, nodejs, electron). For now, I'm keeping it simple with text-only files. I read a file in using
fs.readFile(filePath, function(err, data) {
if (err) {console.log(err);}
typeof callback == "function" && callback(data);
});
Then I create a new file in my database using the data variable. And, now I have something that looks like BinData(0,"SGVsbG8gV29ybGQK") stored in my mongodb. All is fine so far.
Now, what if I wanted to display that file in the UI? In this case, in Electron? I think there are two steps.
Step 1 The first is bringing this variable out of the DB and into the front-end. FYI: The model is called File and the variable that stores the file contents is called content.
So, I've tried File.content.toString() which gives me Object {type: "Buffer", data: Array[7]} which is not the string I'm expecting. What is happening here? I read here that this should work.
Step 2 Display this file. Now, since I'm only using text files right now, I can just display the string I get once Step 1 is working. But, is there a good way to do this for more complex files? Images and GIFs and such?
You should save the file mime.
And then set response.header MIME
response.setHeader("Content-Type", "image/jpeg");
response.write(binary)
response.end()

Piping a file results on a blank file

I have this piece of code in my nodejs app:
function (req, res) {
var serviceUrl = 'http://backend-server:8080/files/123';
require('request').get(serviceUrl).pipe(res);
}
If put http://backend-server:8080/files/123 on the browser it downloads a .pdf file. But when I go through nodejs, it also downloads a .pdf file, but the file is empty.
I can't understand why.
UPDATE: The problem was the connect-livereload middleware. Consider this a duplicate question for this question

Resources