简体   繁体   English

Node.js - 如何编写/序列化包含函数和特殊值的任意 JavaScript 对象并将其保存到 .js 文件

[英]Node.js - How to write/serialize an arbitrary JavaScript object that contains functions and special values and save it to a .js file

I have a JavaScript object that contains functions and special values like Infinity , as well as strings and numbers:我有一个 JavaScript 对象,它包含函数和特殊值,如Infinity ,以及字符串和数字:

const myObject = {
   propertyA: "my string",
   propertyB: 5,
   propertyC: () => "function returing a string",
   propertyD: Infinity
};

I would like to save it to a file so that the resulting content looks like this:我想将它保存到一个文件中,以便生成的内容如下所示:

export default function () {
    return {
        propertyA: "my string",
        propertyB: 5,
        propertyC: () => "function returing a string",
        propertyD: Infinity
    };
}

I have tried to use JSON.stringify() , but that doesn't work with functions and special values, as those are not valid JSON:我曾尝试使用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));

Is there any other way to do this?有没有其他方法可以做到这一点?

You need a different way to serialize your object other than JSON.stringify , maybe something like this:除了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; }

Then, once you have serialized your object, you can save its string representation to a file with some additional code so that you can later load it using require , as you have already done:然后,一旦你序列化了你的对象,你可以将它的string表示保存到一个带有一些附加代码的文件中,以便你以后可以使用require加载它,就像你已经做的那样:

writeFileSync('my-output.js', `export default () => ${ serialized };`);

Or:或者:

writeFileSync('my-output.js', `export default ${ serialized };`);

Note that's just a basic implementation and it doesn't support regular expression, dates, circular structures... So you might prefer to use a library like serialize-javascript or serialize-to-js instead of implementing your own solution.请注意,这只是一个基本实现,它不支持正则表达式、日期、循环结构......所以你可能更喜欢使用像serialize-javascriptserialize-to-js这样的库,而不是实现你自己的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM