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

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);

Related

Using pdfMake.createPdf() is it possible to createPdf from an existing blob?

I would need something like this:
var docDefinition = {
content: [blob]
}
pdfMake.createPdf(docDefinition);
is this possible to set up an existing blob[pdf] inside document definition (using typescript)?
It seems that no, you can't do that with pdfmake.
Pdfmake is used to create/make a pdf file (in a declarative way), what you seem to want to do is to read one. If you want to add a blob to your document-definition-object I believe you can't unfortunately..
I would suggest you to use something else to read a pdf file from binary data. This may do what you want to achieve.

How to create temp files in nodejs

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("..."()

how to check MIME type without hardcoded string

I fetch the file via fetch api.
I finally get something like this:
const result = response.blob()
currently, result.type returns image/jpeg. What I need to do is check if the file returned is a directory or image or text file.
One way is to do this:
if(result.type.includes('image')){
}
I am wondering if there's any other way without hardcoding image string like the above.
mime types never change over time but will be extended, so it's not bad to hard code needed mime types, by the way you can check for image like below,
for images it must start with "image":
result.type.startsWith("image/")
and for text:
result.type.startsWith("text/")
for other types, for example:
let others= ["video/mp4",...]
if(others.indexOf(result.type)>-1)

How go I get csv data into netsuite?

I've got an update to my question.
What I really wanted to know was this:
How do I get csv data into netsuite?
Well, it seems I use the csv import tool to create a mapping and use this call to import the csv nlapiSubmitCSVImport(nlobjCSVImport).
Now my question is: How do I iterate through the object?!
That gets me half way - I get the csv data but I can't seem to find out how I iterate through it in order to manipulate the date. This is, of course, the whole point of a scheduled script.
This is really driving me mad.
#Robert H
I can think of a million reasons why you'd want to import data from a CSV. Billing, for instance. Various reports on data any company keeps and I wouldn't want to keep this in the file cabinet nor would I really want to keep the file at all. I just want the data. I want to manipulate it and I want to enter it.
Solution Steps:
To upload a CSV file we have to use a Suitelet script.
(Note: file - This field type is available only for Suitelets and will appear on the main tab of the Suitelet page. Setting the field type to file adds a file upload widget to the page.)
var fileField = form.addField('custpage_file', 'file', 'Select CSV File');
var id = nlapiSubmitFile(file);
Let's prepare to call a Restlet script and pass the file id to it.
var recordObj = new Object();
recordObj.fileId = fileId;
// Format input for Restlets for the JSON content type
var recordText = JSON.stringify(recordObj);//stringifying JSON
// Setting up the URL of the Restlet
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=108&deploy=1';
// Setting up the headers for passing the credentials
var headers = new Array();
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'NLAuth nlauth_email=amit.kumar2#mindfiresolutions.com, nlauth_signature=*password*, nlauth_account=TSTDRV****, nlauth_role=3';
(Note: nlapiCreateCSVImport: This API is only supported for bundle installation scripts, scheduled scripts, and RESTlets)
Let's call the Restlet using nlapiRequestURL:
// Calling Restlet
var output = nlapiRequestURL(url, recordText, headers, null, "POST");
Create a mapping using Import CSV records available at Setup > Import/Export > Import CSV records.
Inside the Restlet script Fetch the file id from the Restlet parameter. Use nlapiCreateCSVImport() API and set its mapping with mapping id created in step 3. Set the CSV file using the setPrimaryFile() function.
var primaryFile = nlapiLoadFile(datain.fileId);
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId); // Set the mapping
// Set File
job.setPrimaryFile(primaryFile.getValue()); // Fetches the content of the file and sets it.
Submit using nlapiSubmitCSVImport().
nlapiSubmitCSVImport(job); // We are done
There is another way we can get around this although neither preferable nor would I suggest. (As it consumes a lot of API's if you have a large number of records in your CSV file.)
Let's say that we don't want to use the nlapiCreateCSVImport API, so let's continue from the step 4.
Just fetch the file Id as we did earlier, load the file, and get its contents.
var fileContent = primaryFile.getValue();
Split the lines of the file, then subsequently split the words and store the values into separate arrays.
var splitLine = fileContent.split("\n"); // Splitting the file on the basis of lines.
for (var lines = 1,count=0; lines < splitLine.length; lines++)
{
var words = (splitLine[lines]).split(","); // words stores all the words on a line
for (var word = 0; word < words.length; word++)
{
nlapiLogExecution("DEBUG", "Words:",words[word]);
}
}
Note: Make sure you don't have an additional blank line in your CSV file.
Finally create the record and set field values from the array that we created above.
var myRec = nlapiCreateRecord('cashsale'); // Here you create the record of your choice
myRec.setFieldValue('entity', arrCustomerId[i]); // For example, arrCustomerId is an array of customer ID.
var submitRec = nlapiSubmitRecord(myRec); // and we are done
fellow NetSuite user here, I've been using SuiteScripts for a while now but never saw nlobjCSVImport object nor nlapiSubmitCSVImport .. I looked in the documentation, it shows, but there is no page describing the details, care to share where you got the doc from?
With the doc for the CSVImport object I might be able to provide some more help.
P.S. I tried posting this message as a comment but the "Add comment" link didn't show up for some reason. Still new to SOF
CSV to JSON:
convert csv file to json object datatable
https://code.google.com/p/jquery-csv/
If you know the structure of the CSV file, just do a for loop and map the fields to the corresponding nlapiSetValue.
Should be pretty straightforward.

Read JavaScript variables from a file with Python

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database.
For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this:
title: Script title
alias: script_alias
I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this:
var title = "Script title";
var alias = "script_alias";
Is it possible to read these variables with Python easily?
Assuming you only want the two lines, and they are at the top of the file...
import re
js = open("yourfile.js", "r").readlines()[:2]
matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
matches = matcher_rex.match(line)
if matches:
name, value = matches.groups()
print name, value
Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Categories

Resources