首页 > 解决方案 > NodeJS如何调用从另一个文件夹返回字符串的函数

问题描述

我想调用一个从另一个文件夹返回字符串的函数。文件结构如下:

infoString.js 文件代码:

   module.exports = {

    infoHtml: function() {
        let html =
       `<body>
        <h1>$Info</h1>
        <table>
        <tr>
            <td>Product Details:</td>
            <td>${productID}</td>
        </tr>
        </table>
        </body>
        `
        return html;
       }
    }

我尝试在 infoController.js 文件中调用 infoString.js 中的函数,如下所示:

htmlInfo = require("../template/infoString")
const productID = 114455;
let htmlInfoTemplate = htmlInfo.infoHtml();
console.log("HTML Info Template", htmlInfoTemplate); // Does not return the html string from infoHtml function

但它不以某种方式工作。我可以对此发表你的意见吗?我在这里缺少什么吗?

标签: javascripthtmlnode.jsstringfunction

解决方案


试试这个。我没有测试这个。但错误在 htmlInfo = require("../template/infoString")

module.exports = { infoHtml: () => { return ' <body> <h1>$Info</h1> <table> <tr> <td>Product Details:</td> <td>${productID}</td> </tr> </table> </body> '; }, };

将我们要导出的函数和值分配给模块上的导出属性:

const { infoHtml } = require('./user'); 控制台.log( ${infoHtml()} );


推荐阅读