NodeJS:util.inspect对象,里面有函数

问题描述 投票:2回答:1

我有一个像这样的对象:

  const foo = {
    bar: "bar value",

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

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

EG

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]。我该如何做到这一点?

javascript node.js deserialization
1个回答
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的一个属性?),它只是为了给你一个起点。

© www.soinside.com 2019 - 2024. All rights reserved.