How to create temp files in nodejs - javascript

I want to attach an xml file and send as email. I have a string of text which I want to write in an xml file. But I don't want to actually create a file every time.
I am using nodemailer(https://community.nodemailer.com/using-attachments/) to send mail and it supports stream to attach file.
Does stream mean it has to actually create a file? Can't I just use stream somehow to send it as an attachment without creating a file.
I have xml string like this which I want to put in an xml file and send email:
const xmlStringStart = `<ENVELOPE>
<HEADER>
<TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
<IMPORTDATA>
<REQUESTDESC>
<REPORTNAME>All Masters</REPORTNAME>
<STATICVARIABLES>
<SVCURRENTCOMPANY>X</SVCURRENTCOMPANY>
</STATICVARIABLES>
</REQUESTDESC>
<REQUESTDATA>...`;
I saw PassThrough https://nodejs.org/api/stream.html#stream_class_stream_passthrough but can't figure out how to use it.

From the nodemailer document, you can use an utf-8 string as an attachment :
attachments: [ { // utf-8 string as an attachment
filename: 'text1.txt',
content: xmlStringStart // your string
},
]
I think this is simpler and better in your case. The stream option is like, reading the file as a stream then put the content to the attachment.

I would prefer it if I could have a code example to work on, but the basic concept remains the same.
You can just create a file, send it as an attachment through nodemailer, and then delete the file once that action is complete, thus making it act like a temporary file.
//create a txt file and write Hello World into it
fs.writeFileSync("/foo/bar.txt", "Hello World")
/*
Send file as attachment to nodemailer
*/
//once you're done sending file, go ahead and delete it
fs.unlink("/foo/bar.txt")

i think the filename here refers to the displayed filename as its downloaded as attachment. the path option is the file location..
as for passthrough.. it's probably like
const pt = new PassThrough();
{ // stream as an attachment
filename: 'text4.txt',
content: pt
},
then
pt.write("....");
to close: pt.end("..."()

Related

How to get file extension from file content using Node.js

I need some help. I need to fetch what the file type should be from the file containing only using Node.js. I am explaining the scenario below.
Let's say I have some content like below.
let fileContent = "The textContent property sets or returns the text content of the specified node, and all its descendants."
As we can see here the variable fileContent has some text data and I want to write this data into one file. So for that, I need to create the file with a proper extension like abc.txt. Similarly, If fileContent has some json data then I will create the file like abc.json and write the value inside it.
So here I need to fetch what should be the type of file from this content only using Node.js. If anybody has a solution for this will be a great help.
You can use popular file-type package for this. You can send buffer/file/stream/blob as an input and get file type as an output.
const FileType = require('file-type');
...
const { ext, mime } = await FileType.fromBuffer(your_data);

Insert object data into JSON file

I know that it's possible to read and get data of JSON file, but I didn't find any information on how to write an object to JSON file using jQuery. I understand some jQuery, but I dont have any idea how I could do this.
This is the structure of my JSON file:
{
"1": [
"6-5-2015",
"7-5-2015",
"10-5-2015"
]
}
This is an object variable that I want to write into JSON file:
var object = {"2": ["9-5-2015", "14-5-2015", "22-5-2015"]};
How can I push or insert this object to the end of my JSON file and save it, so that the JSON file could look like this?
{
"1": [
"6-5-2015",
"7-5-2015",
"10-5-2015"
],
"2": [
"9-5-2015",
"14-5-2015",
"22-5-2015"
]
}
You cannot write a file locally with Javascript, that would be a major security concern. I suggest you to move the file to your server and do a Public Api where you send the new content and write it server-side. Then request by GET the file in order to read it. Remember that you will have to lock and release the file accordingly in order to avoid loosing changes between requests.
You can't.
JavaScript does not access your disc so it can't directly write into file, so You should have some server side logic.
Reason why it can read that file because on your dist location of that file is URL. But URL on Your drive.
You cannot write a file locally but you can save cookies locally.
For managing cookies with JS you can use a plugin available here..
https://github.com/carhartl/jquery-cookie
//set
var object = {"2": ["9-5-2015", "14-5-2015", "22-5-2015"]};
$.cookie("mydata", object );
....
//get
var object = jQuery.parseJSON($.cookie('mydata'));

Can I save any file in Parse javascript?

I am creating a web application, where in the text area the user can type in anything, and save it as any type of file (.doc, .txt, .java, .js and ect.) Sort of like Notepad, but its on the web. Can I save the file in Parse if the file type is java? I been only able to find tutorials on how to save image files in parse.
Here is my code for saving the file in Parse:
var usercode = req.body.code;
newname = name+".java";
var parsefile = new Parse.File(newname, {base64:usercode});
parsefile.save().then(function(){
console.log("File created and saved in Parse")
}, function(error){
console.log(error);
});
If my code is successful on my console I should see file created and saved in parse. However I don't get anything, not even an error msg.
I believe you can.
Parse stores PFFile's as binary data, as long as you have some way of serializing the data format when it goes in and comes back out it should be fine.
Source: https://parse.com/docs/osx/api/Classes/PFFile.html
Parse.file(Name, content). content must be in byte, these bytes must be stored in array.
So:
var bytes = []
for(x =0; x<content.length; x++){
bytes.push(content.charCodeAt(i));
}
then Parse.file(Name, bytes)

Sending file direct from browser to S3 but changing file name

I am using signed authorized S3 uploads so that users can upload files directly from their browser to S3 bypassing my server. This presently works, but the file name is the same as on the user's machine. I'd like to save it on S3 as a different name.
The formdata I post to amazon looks like this:
var formData = new FormData();
formData.append('key', targetPath); // e.g. /path/inside/bucket/myFile.mov
formData.append('AWSAccessKeyId', s3Auth.AWSAccessKeyId); // aws public key
formData.append('acl', s3Auth.acl); // e.g. 'public-read'
formData.append('policy', s3Auth.policy); // s3 policy including ['starts-with', '$key', '/path/inside/bucket/']
formData.append('signature', s3Auth.signature); // base64 sha1 hash of private key and base64 policy JSON
formData.append('success_action_status ', 200); // response code 200 on success
formData.append('file', file.slice()); // e.g. /path/on/user/computer/theirFile.mov
However instead of the file ending up at:
https://s3.amazonaws.com/mybucket/path/inside/bucket/myFile.mov
It ends up as:
https://s3.amazonaws.com/mybucket/path/inside/bucket/theirFile.mov
Note it has their filename but my base path.
I would like it to have the filename I specify as well.
UPDATE: Update: this was working all along I simply had other code that copied from one bucket to another that restored the original file name and thus confusing me.
Are you sure about the contents of targetPath and where that data comes from?
The behavior you are describing is what should happen in one particular case where targetPath doesn't actually contain /path/inside/bucket/myFile.mov.
I would suggest that targetPath actually contains the value /path/inside/bucket/${filename} -- and by that I mean, literally, the characters $ { f i l e n a m e } are at the end of that string, instead of the filename you intend.
If that's true, that's exactly how it's supposed to work.
If you do not know the name of the file a user will upload, the key value can include the special variable ${filename} which will be replaced with the name of the uploaded file. For example, the key value uploads/${filename} will become the object name uploads/Birthday Cake.jpg if the user uploads a file called Birthday Cake.jpg.
— https://aws.amazon.com/articles/1434
If you populate that variable with the literal filename you want to see in S3, then the uploads should behave as you expect, using your filename instead of the filename on the uploader's computer.
Also, a more secure approach would be to eliminate the key 'starts-with' logic in your policy, and instead explicitly sign a policy (dynamically) for each upload event, with the specific key you want the user to upload. Otherwise, it's not impossible to exploit this form to to overwrite other files within the same key prefix.

How do I encode/decode a file correctly after reading it through javascript and pass the file data through ajax?

I have a django File field with multiple attribute set to true. I am trying to make a multiple file uploader where I get the file objects with a simple javascript FileReader object. After looping through the file list I read the file data through
reader.readAsBinaryString(file);
and get the desired file data result. After passing this data to my views through ajax I am trying to create a copy of the file into the media folder. I am presently using the following views function :
#csrf_exempt
def storeAttachment(data):
'''
stores the files in media folder
'''
data = simplejson.loads(data.raw_post_data)
user_org = data['user_org']
fileName = data['fileName']
fileData = data['fileData']
file_path = MEDIA_ROOT + 'icts_attachments/'
try:
path = open((file_path+ str(user_org) + "_" + '%s')%fileName, "w+")
path.write(fileData)
path.close()
return HttpResponse(1)
except IOError:
return HttpResponse(2)
I am able to write simple text files,.js,.html and other few formats but when I try to upload pdf, word, excel, rar formats I get the following error in my response even though a file with invalid data is saved at my MEDIA path(the file does not open).
'ascii' codec can't encode characters in position 41-42: ordinal not in range(128)
I tried to encode/decode the file data using various references but with no effect..Any advice will be greatly appreciated..
You got error because Python 2's default ASCII encoding was used. Characters greater than 127 cause an exception so use str.encode to encode from Unicode to text/bytes.
Good practice is to use with keyword when dealing with file objects.
path = u''.join((file_path, user_org, '_', fileName)).encode('utf-8')
with open(path, 'w+') as f:
f.write(fileData)

Categories

Resources