首页 > 解决方案 > 如何在nodejs中将变量写入我的JS文件而不评估其值

问题描述

如何使用 node.js 将变量写入 JS 文件?

假设我有以下代码:

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

我只需要替换下面的代码行:

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

现在我当然可以使用 ES6 模板并执行以下操作:

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

但是 thenpageName将被评估为某事并且将不再是一个变量pageName

我将上面的行存储在变量 inner_content 中,然后将其写入 JS 文件,如下所示:

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.

那么如何将变量写入我的 JS 文件呢?

标签: node.js

解决方案


如果我说对了,这就是你能做到的

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

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

只需用单引号或双引号包裹模板即可。


推荐阅读