【发布时间】:2020-12-28 16:56:46
【问题描述】:
我的目标是在 NodeJS 中替换文件中特定位置的值,而不将文件的全部内容加载到 RAM 中(不是 fs.readFileSync(path, "utf8"))。它应该适用于非常大的文件(> 2^28 - 16 字节(V8 允许的最大字符串长度))。
这是我的代码:
const fs = require('fs');
const path = "./text.txt";
const cursor = 1;
(async () => {
await new Promise((res, rej) => {
const buffer = Buffer.from('ee');
fs.open(path, 'w+', function (err, fd) {
if (err) {
console.log('Cant open file');
rej()
} else {
fs.write(fd, buffer, 0, buffer.length, cursor, function (err, writtenbytes) {
if (err) {
console.log('Cant write to file');
rej()
} else {
console.log(writtenbytes +
' characters added to file');
res()
}
})
}
})
})
})()
这是我启动程序之前"./text.txt"的内容:
foo
这是我启动程序后"./text.txt"的内容:
❓ee
并且❓的charCode等于0。
这是预期的结果:
fee
怎么了?我应该解决什么问题?
【问题讨论】:
-
仅供参考,我使用
fs.promises添加了替代答案。
标签: javascript node.js filesystems reader