【问题标题】:Basic query related to the type of the value going to be returned from readFileSync method?与要从 readFileSync 方法返回的值的类型相关的基本查询?
【发布时间】:2018-08-27 21:13:36
【问题描述】:

下面的输出是什么?

const fs = require('fs');

var originalNote = {
  body: 'some body me1',
  title: 'some title'
};

var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
console.log(typeof noteString);
var note = JSON.parse(noteString);
console.log(typeof note);

【问题讨论】:

  • 你为什么不直接运行代码?!
  • 输出为:object object

标签: javascript json node.js


【解决方案1】:

读取文件同步:

Returns: <string> | <Buffer>

指定 'utf8' 作为第二个参数来获取一个字符串。如果未指定编码,则返回原始缓冲区。

var noteString = fs.readFileSync('notes.json', 'utf8');

console.log(typeof noteString);

这是一个字符串,typeof 是 'string' 或 'buffer'

console.log(typeof note);

这取决于字符串的 JSON 值,假设字符串是可解析的 JSON。在你的情况下'对象' .

var aString = '{"foo":"a string"}'
console.log(typeof aString);
var parsed = JSON.parse(aString);
console.log(typeof parsed);

【讨论】:

  • 但是 console.log('typeof noteString') 将对象显示为它的类型
  • 指定 'utf8' 作为第二个参数,否则你可能会得到一个 Buffer 而不是字符串。更新了答案。
  • 但是console.log('typeof originalNoteString');的输出是字符串不是对象那么 typeof noteString 是对象吗??
  • fs 返回一个缓冲区,除非您指定编码。
  • 添加 utf-8 后,console.log('typeof noteString') 中的输出变为字符串;早些时候它显示为对象。 utf-8在这其中的作用是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
相关资源
最近更新 更多