Node.js fs.readFile()是否像PHP的file_get_contents()一样工作?
我有以下脚本读取和打印一个图像作为string:
PHP:
<?php echo file_get_contents("/path/to/small.png");
Node.js的:
var fs = require('fs') var file = fs.readFileSync('/path/to/small.png', 'utf8'); console.log(file)
但是两个脚本输出的string之间有一点点差异。 我用下面的Go代码尝试了同样的事情,输出和PHP的一样:
package main import ( "fmt" "io/ioutil" ) func main() { buf, err := ioutil.ReadFile("/path/to/small.png") if err != nil { panic(err) } content := string(buf) fmt.Println(content) }
所以,有人知道为什么fs.readFile()的行为不同?
垃圾进,垃圾出来 。 如果您告诉Node您的二进制图片文件是一个纯文本文件,编码为UTF-8,那么您无法得到意想不到的结果。
另一方面,您的PHP代码只是输出读取的确切字节数。
var fs = require('fs') var file = fs.readFileSync('/path/to/small.png', 'binary'); console.log(file)
引用:
https://nodejs.org/dist/latest-v7.x/docs/api/fs.html#fs_fs_readfilesync_file_options
https://github.com/nodejs/node/blob/master/lib/buffer.js#L432