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

时间:2019-08-15 19:33:50

标签: javascript node.js file express fs

当我打印一个变量时,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] }
   ]
};

我只想按原样保存格式。

1 个答案:

答案 0 :(得分:1)

尝试一下

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')
    }
});