簡體   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

我有一個 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-javascriptserialize-to-js這樣的庫,而不是實現你自己的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM