javascript JSON.parse(fs.readFileSync()) 返回缓冲区 - 数字字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48818415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:18:15  来源:igfitidea点击:

JSON.parse(fs.readFileSync()) returning a buffer - string of numbers

javascriptnode.js

提问by Conrad Scherb

I'm using a simple Node.js to pull information from a valid jsonfile (checked with JSLint), but the code i'm using doesn't return the expected value:

我正在使用一个简单的 Node.js 从有效的 jsonfile 中提取信息(使用 JSLint 检查),但我使用的代码没有返回预期值:

        squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json'));    

and it returns:

它返回:

{ type: 'Buffer', data: 
[ 123,
 10,
 32,
 32,
 34,
 97,
 99,
 ... 548 more items ] }

Any reason as to why this happens?

关于为什么会发生这种情况的任何原因?

回答by Sidney

fs.readFileSync()returns a Buffer if you don't specify an encoding.

fs.readFileSync()如果未指定编码,则返回 Buffer。

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

So, tell fs.readFileSync()what encoding to use:

所以,告诉fs.readFileSync()使用什么编码:

squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json', 'utf8')); 

回答by Patrick Roberts

The "why" has been answered by Sidney, but a better "what to do" would be to use require(), which supports parsing valid JSON filessynchronously and returning the result as an object:

Sidney已经回答了“为什么” ,但更好的“做什么”是使用require(),它支持同步解析有效的 JSON 文件并将结果作为对象返回:

squadJSON = require('./squads/squad' + whichSquad + '.json');

or even nicer, using an ES6 template literal:

甚至更好,使用 ES6模板文字

squadJSON = require(`./squads/squad${whichSquad}.json`);

One notable difference using require()is that it resolves relative paths from __dirname, which is the directory path of the current module, whereas fsmethods resolve relative pathsusing process.cwd(), or "current working directory", which is the directory the main module of the program is located in.

使用的一个显着区别require()是它从 解析相对路径__dirname,这是当前模块的目录路径,而fs方法使用process.cwd()或“当前工作目录”解析相对路径,这是程序的主模块所在的目录。

Hopefully the examples below demonstrate how their relative path resolution differs:

希望下面的示例展示了它们的相对路径分辨率有何不同:

To make require(...)behave like JSON.parse(fs.readFileSync(..., 'utf8')):

使require(...)行为像JSON.parse(fs.readFileSync(..., 'utf8'))

const { resolve } = require('path');

function readFileSyncJson (path) {
  return require(resolve(process.cwd(), path));
}

And to make JSON.parse(fs.readFileSync(..., 'utf8'))behave like require(...):

并使JSON.parse(fs.readFileSync(..., 'utf8'))行为像require(...)

const { resolve } = require('path');

function requireJson (path) {
  return JSON.parse(fs.readFileSync(resolve(__dirname, path), 'utf8'));
}