Converting stream to string in node.js - node.js

I am reading a file which comes in as an attachment like follows
let content = fs.readFileSync(attachmentNames[index], {encoding: 'utf8'});
When I inspect content, it looks ok, I see file contents but when I try to assign it to some other variable
attachmentXML = builder.create('ATTACHMENT','','',{headless:true})
.ele('FILECONTENT',content).up()
I get the following error
Error: Invalid character in string: PK
There are a couple of rectangular boxes (special characters) after PK in the above message which are not getting displayed.
builder here refers to an instance of the xmlbuilder https://www.npmjs.com/package/xmlbuilder node module.

I fixed this by enclosing the string inside a JS escape() method

Related

NodeJS why is object[0] returning '{' instead of the first property from this json object?

So I have to go through a bunch of code to get some data from an iframe. the iframe has a lot of data but in there is an object called '_name'. the first key of name is 'extension_id' and its value is a big long string. the json object is enclosed in apostrophes. I have tried removing the apostrophes but still instead of 'extension_id_output' I get a single curly bracket. the json object looks something like this
Frame {
...
...
_name: '{"extension_id":"a big huge string that I need"} "a bunch of other stuff":"this is a valid json object as confirmed by jsonlint", "globalOptions":{"crev":"1.2.50"}}}'
}
it's a whole big ugly paragraph but I really just need the extension_id. so this is the code I'm currently using after attempt 100 or whatever.
var frames = await page.frames();
// I'm using puppeteer for this part but I don't think that's relevant overall.
var thing = frames[1]._name;
console.log(frames[1])
// console.log(thing)
thing.replace(/'/g, '"')
// this is to remove the apostrophes from the outside of the object. I thought that would change things before. it does not. still outputs a single {
JSON.parse(thing)
console.log(thing[0])
instead of getting a big huge string that I need or whatever is written in extension_id. I get a {. that's it. I think that is because the whole object starts with a curly bracket. this is confirmed to me because console.log(thing[2]) prints e. so what's going on? jsonlint says this is a valid json object but maybe it's just a big string and I should be doing some kind of split to grab whaat's between the first : and the first ,. I'm really not sure.
For two reasons:
object[0] doesn't return the value an object's "first property", it returns the value of the property with the name "0", if any (there probably isn't in your object); and
Because it's JSON, and when you're dealing with JSON in JavaScript code, you are by definition dealing with a string. (More here.) If you want to deal with the object that the JSON describes, parse it.
Here's an example of parsing it and getting the value of the extension_id property from it:
const parsed = JSON.parse(frames[1]._name);
console.log(parsed.extension_id); // The ID

JSON Object Property Missing Quotation Marks?

I have a very trivial problem, and I'm having trouble finding similar questions. On my Node JS server, I prepare an object of key-value pairs. The keys that have spaces in them are converted to strings like this {'key':'value'}. However, the keys without spaces or special characters don't have quotes surrounding them. When I print it out it looks like this {key:'value'}. The problem is, when I send the response back to the client, the keys without surrounding quotes are missing from the object. So how would I surround all the keys with quotes then so that it is sent properly?
JSON Objects must follow the RFC-7159, the easiest way to get a RFC-compliant JSON object is to use JSON.stringify on the object you want to output on your server side, which is natively supported in NodeJS.
You just need to convert the response to client by converting the javascript object to JSON object.
var object = { key: 'value' };
var newObject = JSON.stringify(object);
console.log("format : ", newObject);
//the JSON.stringify() function definition, it will simply turn the object log into a JSON string.
OUTPUT:
format : '{ 'key' : 'value' }'

In Node.js imported txt file into a variable, but variable doesnt behave like a string

So in node.js I a have read a simple txt file into a variable, but when I want to call whichever string function like split or indexOf on the variable, it doesnt work.
if I do string.indexOf('whatever character'), I become always -1
And if i do string.splice('whichever separator') I become always this on the console: '\u0000s\u0000\r\u0000\n\u0000....'
the code:
const fs = require('fs');
let emails = fs.readFileSync('../model/hotel-emails-with-links-exerc.txt', 'utf-8');
console.log(emails.split('/'));
console.log(emails.indexOf('http'));
this is the content of the file I read : 'youreamil#gmail.com|https://www.hotel-monte.at/de/zimmer-preise/pauschalen.html?offer=27'
If I do console.log(typeof emails) I get 'string' as normal.
However string variables whiches value was not imported from a txt file are working fine.
thanks for the suggestions

Any way to figure out what language a certain file is in?

If I have an arbitrary file sent to me, using Node.js, how can I figure out what language it's in? It could be a PHP file, HTML, HTML with JavaScript inline, JavaScript, C++ and so on. Given that each of these languages is unique, but shares some syntax with other languages.
Are there any packages or concepts available to figure out what programming language a particular file is written in?
You'd need to get the extension of the file. Are you getting this file with the name including the extension or just the raw file? There is no way to tell if you do not either get the file name with the extension or to scan the dir it's uploaded to and grabbing the names of the files, and performing a directory listing task to loop through them all. Node has file system abilities so both options work. You need the file's name with extension saved in a variable or array to perform this. Depending on how you handle this you can build an array of file types by extensions optionally you can try using this node.js mime
Example:
var fileExtenstions = {h : "C/C++ header", php : "PHP file", jar : "Java executeable"};
You can either split the string that contains the files name using split() or indexOf() with substring.
Split Example:
var fileName = "hey.h"; // C/C++/OBJ-C header
var fileParts = fileName.split(".");
// result would be...
// fileParts[0] = "hey";
// fileParts[1] = "h";
Now you can loop the array of extensions to see what it is and return the description of the file you set in the object literal you can use a 2d array and a for loop on the numeric index and check the first index to see it's the extension and return the second index(second index is 1)
indexOf Example:
var fileName = "hey.h";
var delimiter = ".";
var extension = fileName.substring( indexOf( delimiter ), fileName.length );
now loop through the object and compare the value

FreeImage .NET Blank FileName when not constant

Can somebody explain me please why FreeImage library is not recognizing my variable as a valid filename for the method Load, I tried the following code:
var fileName = "C:\\images\\myimage.tif";
var dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TIFF, fileName, 0);
And it's not working, the object dib is always empty (the image is not being loaded), but when I tried the following code:
const string fileName = "C:\\images\\myimage.tif";
var dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TIFF, fileName, 0);
The result is successful, the problem is that I need that image path value to be a normal variable (NOT const), because I work with different images each time, and this images could be anything.
How could I solve this issue, or it's a limitation of the library?
Thanks.
The first thing I see, you are setting the first example as a var instead of string. Define your variable as a string.
I would try that, you dont need the const to make it work I don't believe.
string fileName = "C:\\images\\myimage.tif";

Resources