How to find tmp folder made by nodejs filesystem? - javascript

I was using fs to write values from textarea into a file and had issues with the path until I found on stackoverflow that the path has to be a tmp folder. I did that and the terminal shows the function was successful but now I don't know where that folder is and how I can access.
app.post('/scheduleTweet', function (req, res) {
fs.writeFile('/tmp/scheduleTweet', req.body.text, err => {
if (err) {
console.error(err);
} else{
console.log("success");
}
});
})
Can somebody help me please? I'm self taught so not really sure what to google even.

If the path starts with a /, then fs.writeFile writes to that path on the current drive, for example, to C:/tmp/schedule.txt. Otherwise, it writes relative to the current working directory of the node process. It's easier if you make it relative to the directory containing your Javascript code: fs.writeFile(__dirname + "/tmp/schedule.txt", ...).

Related

fs.rename unable to rename directories with contents on Windows 10

So I've seen several questions similar to this issue but I haven't found anything that quite fixes it.
I'm able to rename a directory with node.js as long as the directory is empty. Once I add contents, I get the error: EPERM: operation not permitted. If I delete the contents, I regain the ability to rename. Is there something simple I'm missing here? Nothing crazy in the code... just can't rename a directory if it has contents.
app.post('/rename', function(req, res, next) {
let _target = req.body.target,
_from = req.body.from,
_to = req.body.to;
fs.renameSync(
'public/' + _target + '/' + _from,
'public/' + _target + '/' + _to,
function(err, data) {
if (err) { sLog(err); return }
res.send('File Renamed');
}
);
});
-- EDIT --
The issue is when the directory has sub directories. Files in the directory to rename don't seem to affect the action
The issue is that I was using nodemon instead of node. Apparently, as a listener, it was locking the files... once I ran everything as node, it functioned as expected.
fs.renameSync doesn't work when the folder is not empty, so you should use another way just like the following:
import fsExtra from "fs-extra";
//then copy and delete, disgusting but work
fsExtra.copySync(oldpath, path);
fsExtra.rmdirSync(oldpath, { recursive: true });

Downloading a zip file from a given path in express api + react

So I'm completely lost at this point. I have had a mixture of success and failure but I can't for the life of me get this working. So I'm building up a zip file and storing it in a folder structure that's based on uploadRequestIds and that all works fine. I'm fairly new to the node but all I want is to take the file that was built up which is completely valid and works if you open it once it's been constructed in the backend and then send that on to the client.
const prepareRequestForDownload = (dirToStoreRequestData, requestId) => {
const output = fs.createWriteStream(dirToStoreRequestData + `/Content-${requestId}.zip`);
const zip = archiver('zip', { zlib: { level: 9 } });
output.on('close', () => { console.log('archiver has been finalized.'); });
zip.on('error', (err) => { throw err; });
zip.pipe(output);
zip.directory(dirToStoreRequestData, false);
zip.finalize();
}
This is My function that builds up a zip file from all the files in a given directory and then stores it in said directory.
all I thought I would need to do is set some headers to have an attachment disposition type and create a read stream of the zip file into the res.send function and then react would be able to save the content. but that just doesn't seem to be the case. How should this be handled on both the API side from reading the zip and sending to the react side of receiving the response and the file auto-downloading/requesting a user saves the file.
This is what the temp structure looks like
There is some strategies to resolve it, all browser when you redirect to URL where extension ending with .zip, normally start downloading. What you can do is to return to your client the path for download something like that.
http://api.site.com.br/my-file.zip
and then you can use:
window.open('URL here','_blank')

How to generate a .txt file with form data and download it with Node JS?

The system has a form, on the side of the backend I recover that data, what I can't do is download that data in a .txt file.
I was using fs.writefile (), but when the system is uploaded in the cloud it does not access the destination folder.
var new_ingreso = new Ingreso(req.body);
//I want to download the data from req.body in a file.txt
fs.writeFile(
'nameFile.txt',
new_ingreso.nameUser,
error => {
if (error)
console.log(error, 'el archivo no fue creado');
else
console.log('El archivo fue creado');
});
}
The file is created without problems what I want is to know if there is any way that this file can be downloaded or if there is another way to download.
He's seeing a way but I'm not sure how to continue.
var file = fs.writeFile(....);
You need to create a route like this. You need to do something with the file path to find your file. No security, code not tested, but it gives you the idea of how to do it.
See https://expressjs.com/en/api.html#res.sendFile
get('file', (req, res) => {
res.sendFile('nameFile.txt', options, function (err) {
if (err) {
next(err)
} else {
console.log('Sent:', 'nameFile.txt')
}
})
})

res.download file from Amazon S3

I am trying to download a file from outside of my root directory however every time I try, it tries to take it from the root directory. I will need the user of my site to be able to download these files.
The file has initially been uploaded to Amazon S3 and I have accessed it using the getObject function.
Here is my code:
app.get('/test_script_api', function(req, res){
var fileName = req.query.File;
s3.getObject(
{ Bucket: "bucket-name", Key: fileName },
function(error, s3data){
if(error != null){
console.log("Failed to retrieve an object: " + error);
}else{
//I have tried passing the S3 data but it asks for a string
res.download(s3data.Body);
//So I have tried just passing the file name & an absolute path
res.download(fileName);
}
}
);
});
This returns the following error:
Error: ENOENT: no such file or directory, stat '/home/ec2-user/environment/test2.txt'
When I enter an absolute path it just appends this onto the end of /home/ec2-user/environment/
How can I change the directory res.download is trying to download from?
Is there an easier way to download your files from Amazon S3?
Any help would be much appreciated here!
I had the same problem and I found this answer:
NodeJS How do I Download a file to disk from an aws s3 bucket?
Based on that, you need to use createReadStream() and pipe().
R here more about stream.pipe() - https://nodejs.org/en/knowledge/advanced/streams/how-to-use-stream-pipe/
res.attachment() will set the headers for you.
-> https://expressjs.com/en/api.html#res.attachment.
This code should work for you (based on the answer in the above link):
app.get('/test_script_api', function (req, res) {
var fileName = req.query.File;
res.attachment(fileName);
var file = s3.getObject({
Bucket: "bucket-name",
Key: fileName
}).createReadStream()
.on("error", error => {
});
file.pipe(res);
});
In my case, on the client side, I used
This made sure that the file is downloading.

Can fs.unlink() delete a empty or non empty folder?

I am new to Node.js.
const fs = require('fs');
fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
This is some code that I copied from a node.js document file system intro example.
But, I am confused. Can unlink() delete a folder or not?
I have tried but it doesn't work.
So, can unlink() delete a folder or not?
The fs.unlink(path, callback) function is used to delete a file not a folder.
To remove a folder you can use the fs.rmdir(path, callback) function instead.

Categories

Resources