[英]Node.js - How to write/serialize an arbitrary JavaScript object that contains functions and special values and save it to a .js file
我有一个 JavaScript 对象,它包含函数和特殊值,如Infinity
,以及字符串和数字:
const myObject = {
propertyA: "my string",
propertyB: 5,
propertyC: () => "function returing a string",
propertyD: Infinity
};
我想将它保存到一个文件中,以便生成的内容如下所示:
export default function () {
return {
propertyA: "my string",
propertyB: 5,
propertyC: () => "function returing a string",
propertyD: Infinity
};
}
我曾尝试使用JSON.stringify()
,但这不适用于函数和特殊值,因为它们不是有效的 JSON:
writeFileSync('my-output.js', `
export default function () {
return ${ JSON.stringify(myObject) };
}
`);
const myObject = { propertyA: "my string", propertyB: 5, propertyC: () => "function returing a string", propertyD: Infinity }; console.log(JSON.stringify(myObject, null, 4));
有没有其他方法可以做到这一点?
除了JSON.stringify
,您需要一种不同的方法来序列化您的对象,可能是这样的:
// Pretty: const TAB = ' '; const BR = '\\n'; const CBR = `,${ BR }`; // Minified: // const TAB = ''; // const BR = ''; // const CBR = ','; function arrayAsString(arr, depth=0) { const _ = TAB.repeat(depth - 1); const __ = _ + TAB; return `[${ BR }${ arr.map(value => `${ __ }${ serialize(value, depth) }`).join(CBR) }${ BR }${ _ }]`; } function objectAsString(obj, depth=0) { const _ = TAB.repeat(depth - 1); const __ = _ + TAB; return `{${ BR }${ Object.entries(obj).map(([key, value]) => `${ __ }${ key }: ${ serialize(value, depth) }`).join(CBR) }${ BR }${ _ }}`; } function serialize(value, depth=0) { if (value === null) { return `${ value }`; } else if (Array.isArray(value)) { return arrayAsString(value, depth + 1); } else if (typeof value === 'object') { return objectAsString(value, depth + 1); } else if (typeof value === 'string') { return `"${ value }"`; } else { return `${ value }`; } } const notStringifyableObject = { 1: Infinity, str: "my string", num: 5, func: () => console.log('It works! 🎉'), mixArr: [{ value: 1 }, { value: 2 }, 1, 2, [3, 4, 5]], arr: [1, 2, 3], obj: { foo: 'bar' }, nil: null, und: undefined }; const serialized = serialize(notStringifyableObject); // This is what you would save in a file: console.log(`export default ${ serialized };`); // Check if it's actually working: eval(`test = ${ serialized }`); test.func();
.as-console-wrapper { max-height: 100vh !important; }
然后,一旦你序列化了你的对象,你可以将它的string
表示保存到一个带有一些附加代码的文件中,以便你以后可以使用require
加载它,就像你已经做的那样:
writeFileSync('my-output.js', `export default () => ${ serialized };`);
或者:
writeFileSync('my-output.js', `export default ${ serialized };`);
请注意,这只是一个基本实现,它不支持正则表达式、日期、循环结构......所以你可能更喜欢使用像serialize-javascript
或serialize-to-js
这样的库,而不是实现你自己的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.