JavaScript 将控制台临时变量数组保存到本地文件 (不使用 Node.js)
本文将介绍如何将 JavaScript 控制台中的临时变量数组保存到本地文件,而不使用 Node.js。
通常情况下,我们会使用 JSON.stringify(arr) 方法将数组转换为 JSON 字符串,然后写入本地文件。但是,如果数组中包含循环引用的对象,就会出现以下错误:
'starting at object with constructor 'Object' | property 'children' -> object with constructor 'Array' | index 0 -> object with constructor 'Object' | property '__node' -> object with constructor 'Object' --- property 'parent' closes the circle'
这个错误是因为 JSON.stringify() 方法无法处理循环引用的对象。
为了解决这个问题,我们可以使用第三方库,例如 circular-json 或 flatted。这些库可以处理循环引用的对象,并将其转换为合法的 JSON 字符串。
以下示例代码展示了如何使用 circular-json 库将数组类型转存到本地文件:
// 引入 circular-json 库
const CircularJSON = require('circular-json');
// 假设有一个临时变量数组
const arr = [1, 2, 3];
// 将数组转换为 JSON 字符串
const jsonStr = CircularJSON.stringify(arr);
// 将 JSON 字符串写入本地文件
const fs = require('fs');
fs.writeFileSync('data.json', jsonStr);
这段代码首先引入 circular-json 库,然后使用 CircularJSON.stringify() 方法将数组转换为 JSON 字符串,最后使用 Node.js 的 fs 模块将 JSON 字符串写入本地文件 data.json 中。
如果要在浏览器中执行类似的操作,可以使用 Blob 对象将字符串保存为文件。
原文地址: https://www.cveoy.top/t/topic/ovMp 著作权归作者所有。请勿转载和采集!