NodeJS:内置函数的util.inspect对象

时间:2019-04-08 14:49:30

标签: 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]。我该如何完成?

1 个答案:

答案 0 :(得分:2)

这很棘手,但是由于您是在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的一个属性,该怎么办?),这只是为了给您一个起点。点。

相关问题