gpt4 book ai didi

javascript - node.js/读取文件的前 100 个字节

转载 作者:IT老高 更新时间:2023-10-28 23:07:55 28 4
gpt4 key购买 nike

我正在尝试分段读取文件:前 100 个字节,然后……我正在尝试读取 /npm 文件的前 100 个字节:

app.post('/random', function(req, res) {
var start = req.body.start;
var fileName = './npm';
var contentLength = req.body.contentlength;
var file = randomAccessFile(fileName + 'read');
console.log("Start is: " + start);
console.log("ContentLength is: " + contentLength);
fs.open(fileName, 'r', function(status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(contentLength);
fs.read(fd, buffer, start, contentLength, 0, function(err, num) {
console.log(buffer.toString('utf-8', 0, num));
});
});

输出是:

Start is: 0
ContentLength is: 100

以及下一个错误:

fs.js:457
binding.read(fd, buffer, offset, length, position, wrapper);
^
Error: Length extends beyond buffer
at Object.fs.read (fs.js:457:11)
at C:\NodeInst\node\FileSys.js:132:12
at Object.oncomplete (fs.js:107:15)

可能是什么原因?

最佳答案

您混淆了偏移量和位置参数。来自 the docs :

offset is the offset in the buffer to start writing at.

position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

你应该把你的代码改成这样:

    fs.read(fd, buffer, 0, contentLength, start, function(err, num) {
console.log(buffer.toString('utf-8', 0, num));
});

基本上是 offset is 将是 fs.read 将写入缓冲区的索引。假设您有一个长度为 10 的缓冲区,如下所示:<Buffer 01 02 03 04 05 06 07 08 09 0a>你会读到/dev/zero基本上只有零,并将偏移量设置为 3 并将长度设置为 4 然后你会得到:<Buffer 01 02 03 00 00 00 00 08 09 0a> .

fs.open('/dev/zero', 'r', function(status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
fs.read(fd, buffer, 3, 4, 0, function(err, num) {
console.log(buffer);
});
});

还可以使用 fs.createStream 制作您可能想尝试的东西:

app.post('/random', function(req, res) {
var start = req.body.start;
var fileName = './npm';
var contentLength = req.body.contentlength;
fs.createReadStream(fileName, { start : start, end: contentLength - 1 })
.pipe(res);
});

关于javascript - node.js/读取文件的前 100 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720032/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com