Alexander Solonik
Alexander Solonik

Reputation: 10230

How do i write a variable to my JS file in nodejs without evaluating its value

How do i write a variable to a JS file using node.js ?

Suppose i have the below code:

function openPage(pageName) {
    window.location.href = 'melt://navigatetoitem:' + pageName + '.html';
}

I only need to replace the below line of code:

window.location.href = 'melt://navigatetoitem:' + pageName + '.html';

Now ofcourse i can use ES6 templating and do something like:

`window.location.href = melt://navigatetoitem: ${pageName} .html`;

But then pageName will be evaluated to something and will no longer be a variable pageName.

I store the above line in a variable inner_content and then write it to the JS file like below:

let inner_content =  `window.location.href = melt://navigatetoitem: ${pageName} .html`;
fs.writeFileSync( path_Url , inner_content , 'utf-8'); // path_Url is the path of my js file.

So how do i go about writing a variable to my JS file ?

Upvotes: 1

Views: 58

Answers (2)

Alexander Solonik
Alexander Solonik

Reputation: 10230

I used a bit of a ridiculous solution , nevertheless it worked , below is the code:

elem.toString().replace( /window.location.href/g , 'document.location' )
               .replace( /melt:\/\/navigatetoitem:/g , '')
               .replace( /.html/g , '.zip'); 

Upvotes: 1

Med Djelaili
Med Djelaili

Reputation: 34

if I got you right, this how you can do it

let inner_content =  '`window.location.href = melt://navigatetoitem: ${pageName} .html`';

fs.writeFileSync( path_Url , inner_content , 'utf-8');

simply by wrapping the template with a single or double quote.

Upvotes: 2

Related Questions