javascript - NodeJS : util. 检查内部有函数的对象

标签 javascript node.js deserialization

我有一个像这样的对象:

  const foo = {
    bar: "bar value",

    baz() {
      console.log(this.bar);
    },
  };

我想使用fs.writeFileSyncutil.inspect将此对象写入单独的js文件

例如

fs.writeFileSync("newfile.js", "exports.config = " + 
util.inspect(foo, { showHidden: false, compact: false, depth: null }));

这让我获得了包含以下内容的文件newfile.js:

exports.config = {
  bar: 'bar value',
  baz: [Function: baz]
}

我需要将函数 baz 公开,就像它在原始对象 foo 中的公开方式一样,而不是显示为 [Function: baz]。我该如何实现这个目标?

最佳答案

这很棘手,但由于您是在 Node.js 上执行此操作,因此您不必担心不同 JavaScript 引擎的变化,这很好。

您需要使用最近标准化的Function.prototype.toString。您的 baz 是一个方法,因此 toString 返回它的方法定义,但其他函数可能会以函数声明、函数表达式、箭头的形式出现功能等

这应该可以帮助您开始:

const strs = [];
for (const [name, value] of Object.entries(foo)) {
    if (typeof value === "function") {
        const fstr = value.toString().trim();
        if (fstr.startsWith("function") || fstr[0] === "(") {
            strs.push(`${name}: ${fstr}`);
        } else {
            strs.push(fstr); // probably a method
        }
    } else {
        strs.push(`${name}: ${JSON.stringify(value)}`);
    }
}
const sep = "\n    ";
const str = `exports.config = {${sep}${strs.join(`,${sep}`)}\n};`;

实时示例(如果您没有使用具有 V8 的浏览器(例如 Chrome、Chromium、Brave),那么这可能不起作用):

const foo = {
    bar: "bar value",

    biz: function() {
        // This is a function assigned to a property
        return this.bar;
    },
    
    buz: function() {
        // This is an arrow function assigned to a property
        // VERY surprising that this comes out as a traditional function
        return this.bar.toUpperCase();
    },
    
    baz() {
        // This is a method
        console.log(this.bar);
    },
};
const strs = [];
for (const [name, value] of Object.entries(foo)) {
    if (typeof value === "function") {
        const fstr = value.toString().trim();
        if (fstr.startsWith("function") || fstr[0] === "(") {
            strs.push(`${name}: ${fstr}`);
        } else {
            strs.push(fstr); // probably a method
        }
    } else {
        strs.push(`${name}: ${JSON.stringify(value)}`);
    }
}
const sep = "\n    ";
const str = `exports.config = {${sep}${strs.join(`,${sep}`)}\n};`;
console.log(str);
.as-console-wrapper {
  max-height: 100% !important;
}

显然这里还有很大的改进空间(例如,如果对象中有一个函数分配给 foo 的属性之一怎么办?),它只是为了给你一个起点。

关于javascript - NodeJS : util. 检查内部有函数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55576138/

相关文章:

javascript - 有没有办法使用 CSS 或 javascript 从另一个 CSS 样式引用现有的 CSS 样式?

javascript - Node js如何处理文件响应

java - 如果值不是 Json 格式,则不反序列化值

java - 反序列化对象时出现 EOFException

javascript - 调用 res.render() 后会发生 Mongoose 查找吗?

javascript - 如何在代码的其他部分调用此函数?

javascript - 如何使 this 引用函数中的类?

当我尝试通过 GCP 部署命令托管 Node.js 应用程序时,它不起作用。错误 : Cannot find module 'express'

javascript - 如何从使用 node-oracledb 进行的查询返回回调?

java - Jackson 的 mixin 类不能解决问题 : bug or am I doing something wrong?