Line breaks in a YAML file - javascript

I'm using javascript to write a YAML file, but it's invalid.
I'm writing it with one string using \n line breaks:
'dir: ./_data/'+language+'\npath: '+options.path+'\nname: work'
My question is, is this the correct way to break between the vars in a YAML file? It does not seem to validate.

It is difficult to say without knowing what the language and options.path variables are.
This:
dir: ./_data/some_language
path: some_options.path
name: work
is valid YAML, even if you don't have a newline at the end of the file (I recommend to put a \n at the end of your string).
However if the variable options.path starts with a * you'll get an error about an undefined alias. If that value has : (colon + space) in it you'll get an error as well (mapping values not allowed).
You will also get an error if there are spaces before the first key (dir).
So it could generate correct YAML, but it might generate invalid YAML, depending on the values of the variables. The line breaks however, are at the right place.

Related

Translation string extraction

We have a translation extraction tool that we've written, that extracts strings that we've marked for translation in TypeScript. The JavaScript tool reads our Typescript files and has a regex like:
fileContent.match(/this.\translate\((.*?));/);
(simplified for readability, this works fine)
The translation method takes 3 parameters: 1. The string to be translated, 2. any variables that might be interpolated, 3. description. The last 2 are optional.
Examples of the implementation:
this.translate('text to translate');
this.translate('long text' +
'over multiple lines');
this.translate(`text to translate with backticks for interpolation`);
this.translate(`some test with a ${variable}`, [variable]);
this.translate(`some test with a ${variable}`, [variable], 'Description');
We need to extract these 3 parameters from text in JavaScript and have issues parsing it. We are currently using a regex to check the first opening string character (' or "`") and trying to match a closing character, but that is hard to do.
I'm currently trying to use eval (the script doesn't run in the browser, but CLI), like this:
function getParameters(text, variables, description){
return {text: text, variables: variables, description: description}
}
toEval = string.replace('this.translate', 'getParameters');
eval(toEval);
Which works perfect if there are no variables, but complains that "variables" not defined, when we pass in variables.
Can anyone suggest a good/better way to deal with this text extraction?
Instead of regex, you can use either babel or webpack to properly parse Javascript (or typescript) and extract all the information.
I have a webpack plugin that works on static strings only, but it should give a good starting point:
https://github.com/grassator/webpack-extract-translation-keys

Stripping filename from HTML Encoded UNIX Path

I am writing a NodeJS application using Express and Google Datastore. I am trying to get the filename from a UNIX path. The path is stored in an HTML encoded format in the database.
Here's the path un-encoded:
/toplevel/example/text123.txt
Here's how the path is stored in the database HTML encoded format:
/toplevel/example/test123.txt
Since the path is HTML encoded, this line is not working.
let filename_only = requested_filepath_unescaped.split('/').pop().toString();
I also tried splitting by the encoded characters but that does not work either (perhaps because split doesn't work with multiple characters?)
let filename_only = requested_filepath_unescaped.split('&#x2F').pop().toString();
What is the best way to either split the string as-is, or de-code the HTML back into an unencoded string?
Well, split works with multiple characters, so I don't know what goes wrong when you tried it.
However if you can use jQuery, you can also decode the html like this:
var htmlDecoded = $('<div />').html(htmlEncoded).text()
After that you can split on '/'.
(The code I gave creates a div tag in memory (it is not added to the DOM, the web page), after that it sets the html of it, which automatically decodes the html entities.
EDIT:
As I am unsure what the problem of the OP is and I can't comment due to low reputation, I give some more suggestions here.
Maybe the variable you call split on is not really a string object. Try converting to string first:
var filename = filepath.toString().split('/');
Other option is to use regex, but I don't know what exactly solves that, but might be worth trying.
var filename = filepath.toString().split(/&#2F;/);
EDIT2: Tested and working in Chrome v62 and Node v6.11.4.

Unterminated string constant-mshta:javascript

Recently I was trying to get a quick alert box from javascript using mshta but I noticed something strange and I have no ideea what the problem is. This is,in a way,what I was trying to achieve:
mshta javascript:alert("The file was stored here:\"C:\\folder_with_space_ _.txt");
The error it gives is the one in the title of this post(char 57).I tried a combination of things and:
//code that works:
mshta javascript:alert("The file was stored here:\"sdadasd");
mshta javascript:alert("The file was stored here:\"\" sdadasd");
//error-notice the space;error on char 35
mshta javascript:alert("The file was stored here:\" sdasds");
It looks like it's giving error when the number of double-quotes is odd,but:
//error
mshta javascript:alert("The file was stored here:\" \"sdadasd");
I tried to do the same in a browser console and it worked. I believe is some kind of parser-error.How can I fix it?(I am thinking of using fromCharCode to directly insert the double quote).
Note: the commands were run from cmd.
I'll start off with the version of the command that I got to work, and I'll explain why it works:
mshta "javascript:alert('The file was stored here:\x22C:\\folder_with_space_ _.txt');"
The first and perhaps most important point is that we are passing a single argument to mshta.exe (the JavaScript command to execute), so we should surround that entire argument in double quotes. This prevents the space from being treated as an argument delimiter.
The second point is that there doesn't seem to be a way to have double quotes inside the actual JavaScript commands. According to the question Escaping Double Quotes in Batch Script, there is no standard for escaping double quotes inside double quotes for cmd. Apparently, mshta.exe doesn't honor "" or \" (or at least, I couldn't get them to work). I suggest following Teemu's suggestion in the comments and use single quotes only for string delimiter in the JavaScript code. If, inside a string, you want to include a double quote character, use the hex literal \x22.

NodeJS escaping back slash

I am facing some issues with escaping of back slash, below is the code snippet I have tried. Issues is how to assign a variable with escaped slash to another variable.
var s = 'domain\\username';
var options = {
user : ''
};
options.user = s;
console.log(s); // Output : domain\username - CORRECT
console.log(options); // Output : { user: 'domain\\username' } - WRONG
Why when I am printing options object both slashes are coming?
I had feeling that I am doing something really/badly wrong here, which may be basics.
Update:
When I am using this object options the value is passing as it is (with double slashes), and I am using this with my SOAP services, and getting 401 error due to invalid user property value.
But when I tried the same with PHP code using same user value its giving proper response, in PHP also we are escaping the value with two slashes.
When you console.log() an object, it is first converted to string using util.inspect(). util.inspect() formats string property values as literals (much like if you were to JSON.stringify(s)) to more easily/accurately display strings (that may contain control characters such as \n). In doing so, it has to escape certain characters in strings so that they are valid Javascript strings, which is why you see the backslash escaped as it is in your code.
The output is correct.
When you set the variable, the escaped backslash is interpreted into a single codepoint.
However, options is an object which, when logged, appears as a JSON blob. The backslash is re-escaped at this point, as this is the only way the backslash can appear validly as a string value within the JSON output.
If you re-read the JSON output from console.log(options) into javascript (using JSON.parse() or similar) and then output the user key, only one backslash will show.
(Following question edit:)
It is possible that for your data to be accepted by the SOAP consuming service, the data needs to be explicitly escaped in-band. In this case, you will need to double-escape it when assigning the value:
var s = 'domain\\\\user'
To definitively determine whether you need to do this or not, I'd suggest you put a proxy between your working PHP app and the SOAP app, and inspect the traffic.

Parsing text into javascript String

I am trying to parse some text into javascript strings. In essence I have a String in javascript containing what would be another javascript string. Here are some samples that I have in my tests:
input1: '"This \\"should\\" work"'
output1: 'This "should" also work'
input2: '"Another working \\nstring\\n with newlines"'
output2: 'Another working \nstring\n with newlines'
// Should throw an exception since it would escape the last ":
input3: '"This should not work\\"'
// Should throw an exception since it contains an illegal newline
input4: '"This \n should also not work"'
I was considering using eval on the input strings but it feels like a hack and I am unsure if it is safe. It doesn't yield an error on the input3 sample when I try it in Node.It works when running my tests but not when used I run: eval('"This should not work\\"') in Node directly.
How can I parse the above sample inputs to their corresponding outputs and still get errors for the bad samples?
EDIT:
My initial atempt:
output = input.slice(1, input.length - 1)
My second atempt:
output = eval(input);
Using eval seems to work , but feels like a hack.

Categories