我正在使用Node.js创建一个应用程序,并且试图读取一个名为“ datalog.txt”的文件。我使用“追加”功能写入文件:
//Appends buffer data to a given file
function append(filename, buffer) {
let fd = fs.openSync(filename, 'a+');
fs.writeSync(fd, str2ab(buffer));
fs.closeSync(fd);
}
//Converts string to buffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
append("datalog.txt","12345");
这看起来很棒。但是,现在我想fs.readFileSync
用来读取文件。我尝试使用此:
const data = fs.readFileSync('datalog.txt', 'utf16le');
我将编码参数更改为Node文档中列出的所有编码类型,但所有这些均导致此错误:
TypeError: Argument at index 2 is invalid: Invalid encoding
我要做的就是能够从“ datalog.txt”中读取数据。任何帮助将不胜感激!
注意:一旦我可以读取文件的数据,我希望能够获得文件所有行的列表。
好的,经过数小时的故障排除后,查看了文档后,我找到了一种解决方法。
try {
// get metadata on the file (we need the file size)
let fileData = fs.statSync("datalog.txt");
// create ArrayBuffer to hold the file contents
let dataBuffer = new ArrayBuffer(fileData["size"]);
// read the contents of the file into the ArrayBuffer
fs.readSync(fs.openSync("datalog.txt", 'r'), dataBuffer, 0, fileData["size"], 0);
// convert the ArrayBuffer into a string
let data = String.fromCharCode.apply(null, new Uint16Array(dataBuffer));
// split the contents into lines
let dataLines = data.split(/\r?\n/);
// print out each line
dataLines.forEach((line) => {
console.log(line);
});
} catch (err) {
console.error(err);
}
希望它可以帮助遇到同样问题的其他人!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句