1

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 ?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.