我有一个像这样的对象:
const foo = {
bar: "bar value",
baz() {
console.log(this.bar);
},
};
我想使用fs.writeFileSync
和util.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/