简体   繁体   English

Node js中这种输出背后的原因是什么?

[英]What is the reason behind this kind of output in node js?

Nodejs output shows somewhat a Buffer value, for the following code: 对于以下代码,Nodejs输出会显示一些Buffer值:

'use strict'

var fs;
fs = require("fs");

const output = fs.readFileSync('note.text');
console.log(output);

output: 输出:

<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a 73 68 61 67 65 65 73 68 61 0d 0a 73 6c 6c 69 74 0d 0a>
'use strict'

var fs;
fs = require("fs");

output = fs.readFileSync('note.text');
output = output.toString('utf8');
console.log(output);

That readFile function reads as Buffer/Stream, you have to convert it to readable form. 该readFile函数读取为Buffer / Stream,您必须将其转换为可读形式。

You're reading the filestream and printing the stream, not the text representation. 您正在读取文件流并打印流,而不是文本表示。 What you see printed in the hex representation of the data in the stream 您在流中数据的十六进制表示中看到的内容

hello world
shageesha
sllit

If the encoding option is specified then this function returns a string. 如果指定了encoding选项,则此函数返回一个字符串。 Otherwise it returns a buffer. 否则,它将返回一个缓冲区。

fs.readFileSync(path[, options])

like this: 像这样:

var fs = require('fs');
const output = fs.readFileSync('note.text', 'utf8');
console.log(output);

The character encodings currently supported by Node.js include: Node.js当前支持的字符编码包括:

'ascii' - For 7-bit ASCII data only. 'ascii'-仅适用于7位ASCII数据。 This encoding is fast and will strip the high bit if set. 这种编码速度很快,如果置位,它将去除高位。

'utf8' - Multibyte encoded Unicode characters. 'utf8'-多字节编码的Unicode字符。 Many web pages and other document formats use UTF-8. 许多网页和其他文档格式都使用UTF-8。

'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. 'utf16le'-2或4个字节的,低端编码的Unicode字符。 Surrogate pairs (U+10000 to U+10FFFF) are supported. 支持代理对(U + 10000至U + 10FFFF)。

'ucs2' - Alias of 'utf16le'. 'ucs2'-'utf16le'的别名。

'base64' - Base64 encoding. 'base64'-Base64编码。 When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. 从字符串创建缓冲区时,此编码还将正确接受RFC4648第5节中指定的“ URL和文件名安全字母”。

'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). 'latin1'-一种将缓冲区编码为一个字节编码的字符串的方式(由RFC1345第63页中的IANA定义,将其作为Latin-1补充块和C0 / C1控制代码)。

'binary' - Alias for 'latin1'. 'binary'-'latin1'的别名。

'hex' - Encode each byte as two hexadecimal characters. 'hex'-将每个字节编码为两个十六进制字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM