使用 nodejs fs.writeFile 在文件中写入相同的格式

write the same format in file using nodejs fs.writeFile

Node Js 当我打印一个变量时,我得到这样的值

    Supercluster {
          options: { log: true, radius: 60, extent: 512, maxZoom: 16 },
          trees:
           [ KDBush {
               nodeSize: 64,
               points: [Array],
               ids: [Uint16Array],
               coords: [Float32Array] },
             KDBush {
               nodeSize: 64,
               points: [Array],
               ids: [Uint16Array],
               coords: [Float32Array] },
             KDBush {
               nodeSize: 64,
               points: [Array],
               ids: [Uint16Array],
               coords: [Float32Array] }
     ]};

我想把它写到一个文件中。我正在使用下面的代码

fs.writeFile('./filename.json', json, err => {
    if (err) {
        console.log('Error writing file', err)
    } else {
        console.log('Successfully wrote file')
    }
});

创建执行文件后,但仅在文件内部 [object Object]

然后我使用了 JSON.stringify(clusterPacked) 但我的值格式发生了变化

Supercluster 和 KDBush 都被删除了,我的输出就像

{ options: { log: true, radius: 60, extent: 512, maxZoom: 16 },
  trees:
   [ { nodeSize: 64, points: [Array], ids: [Object], coords: [Object] },
     { nodeSize: 64, points: [Array], ids: [Object], coords: [Object] }
   ]
};

我只想按原样保存格式。

试试这个,

const fs = require('fs');
const util = require('util');

fs.writeFile('./filename.json', util.inspect(json), err => {
    if (err) {
        console.log('Error writing file', err)
    } else {
        console.log('Successfully wrote file')
    }
});