【问题标题】:write the same format in file using nodejs fs.writeFile使用nodejs fs.writeFile在文件中写入相同的格式
【发布时间】:2019-12-22 05:16:51
【问题描述】:

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

我只想按原样保存格式。

【问题讨论】:

    标签: javascript node.js file express fs


    【解决方案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')
        }
    });
    
    

    【讨论】:

    • 我在 JSON.parse () 的位置 1 处的 JSON 中收到错误 Unexpected token o
    • @NathanSrivi 我已经编辑了答案以包含使用util.inspect(...) 的第二种方法。你能试试吗?
    • 对不起,这是我的错误。它运行良好。非常感谢您的帮助
    • 最后一个小问题如何读取这个存储值?正常阅读会起作用还是需要做任何其他事情?
    • @NathanSrivi 使用fs 正常读取应该可以工作。如果您遇到任何问题,请告诉我
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2017-09-14
    • 2020-12-09
    • 2021-09-23
    • 2019-11-04
    相关资源
    最近更新 更多