Node.js如何删除文件中的前N个字节?

3
如何在不将其加载到内存中的情况下删除(删除|修剪)二进制文件的前N个字节?
我们有`fs.ftruncate(fd,len,callback)`,它会从文件末尾剪切字节(如果文件更大)。
如何在Node.js中从开头裁剪字节或修剪开头而无需读取文件并将其加载到内存中?
我需要像`truncateFromBeggining(fd,len,callback)`或`removeBytes(fd,0,N,callback)`这样的东西。
如果不可能实现,使用文件流最快的方法是什么?
引用:
在大多数文件系统上,您不能“剪切”文件的开头或中间的一部分,只能在末尾截断它。
考虑到上面的情况,我想,我们可能必须打开输入文件流,找到第N个字节之后,并将其余字节复制到输出文件流。
2个回答

1

你正在请求一个操作系统文件系统操作:即能够在原地删除文件开头的一些字节,而无需重写整个文件。

你正在请求一个不存在的文件系统操作,至少在Linux / FreeBSD / MacOS / Windows中是如此。

如果你的程序是文件的唯一用户并且它适合RAM,那么最好的选择是将整个文件读入RAM,然后重新打开文件进行写入,然后写出你想要保留的部分。

或者你可以创建一个新文件。假设你的输入文件名为q。然后你会创建一个名为new_q的文件,并附加一个流。你会将你想要的内容传输到新文件中。然后你会unlink(删除)输入文件q,并rename输出文件new_qq

注意:这个取消链接/重命名操作会创建一个短暂的时间段,在这段时间内没有名为q的文件可用。所以如果其他程序尝试打开它并找不到它,应该再试几次。
如果您正在创建一个队列方案,您可能考虑使用一些其他方案来保存您的队列数据。这个文件读取/重写/取消链接/重命名序列在重负载下有很多错误可能性。(问问我如何知道当你有几个小时的空闲时间时;-) redis值得一看。

0

我决定用 bash 解决这个问题。

脚本首先会截短位于 temp 文件夹中的文件,然后将它们移回原始文件夹。

使用 tail 来执行截短操作:

tail --bytes="$max_size" "$from_file" > "$to_file"

完整脚本:
#!/bin/bash

declare -r store="/my/data/store"
declare -r temp="/my/data/temp"
declare -r max_size=$(( 200000 * 24 ))

or_exit() {
    local exit_status=$?
    local message=$*

    if [ $exit_status -gt 0 ]
    then
        echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
        exit $exit_status
    fi
}

# Checks if there are any files in 'temp'. It should be empty.
! ls "$temp/"* &> '/dev/null'
    or_exit 'Temp folder is not empty'

# Loops over all the files in 'store'
for file_path in "$store/"*
do
    # Trim bigger then 'max_size' files from 'store' to 'temp'
    if [ "$( stat --format=%s "$file_path" )" -gt "$max_size" ]
    then
        # Truncates the file to the temp folder
        tail --bytes="$max_size" "$file_path" > "$temp/$(basename "$file_path")"
            or_exit "Cannot tail: $file_path"
    fi
done
unset -v file_path

# If there are files in 'temp', move all of them back to 'store'
if ls "$temp/"* &> '/dev/null'
then
    # Moves all the truncated files back to the store
    mv "$temp/"* "$store/"
        or_exit 'Cannot move files from temp to store'
fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接