简体   繁体   中英

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

Nodejs output shows somewhat a Buffer value, for the following code:

'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.

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. 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:

'ascii' - For 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.

'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

'ucs2' - Alias of 'utf16le'.

'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5.

'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).

'binary' - Alias for 'latin1'.

'hex' - Encode each byte as two hexadecimal characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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