2017-05-30 46 views
-1

我有一个未知大小的文件test.txt。与其他服务共享文件,我必须从这个文件读取编辑它。只需稍稍编辑即可更改时间戳。 什么是编辑它而不读取整个文件并重新写入的最佳方式。我不认为这是一个正确的方法来做到这一点。我知道createReadStream和createWriteStream,但我不想复制文件并浪费资源,特别是内存。 谢谢。编辑节点中的大文件

+0

没有测试,只是快速搜索:https://stackoverflow.com/questions/14177087/replace-a-string-in-a-file-with-nodejs – dward

+1

@dward - 对接受的答案问题究竟是什么这个问题试图避免 – Quentin

+1

使用流不会浪费大量的内存。 – SLaks

回答

0

如果你只是想改变时间戳,你可以使用fs.futimes()。版本号为v0.4.2的节点为原生节点。

var fs = require("fs"); 

var fd = fs.openSync("file"); // Open a file descriptor 

var now = Date.now()/1000; 
fs.futimesSync(fd, now, now); // Modify it by (fd, access_time, modify_time) 

fs.closeSync(fd); // Close file descriptor 

这样,你不依赖于任何NPM包。

你可以在这里阅读更多:https://nodejs.org/api/fs.html#fs_fs_futimes_fd_atime_mtime_callback

+0

是的,谢谢,但这里的时间戳是比喻,我的真实情况是一个字符串将被改为另一个随机字符串。 – jalal246

+0

@JimmyJanson所以你想改变文件的内容,对吧?我以为只是想改变文件时间戳。 –

+0

是的,我认为把时间戳的内容使问题更容易理解。 – jalal246

0

你需要像触摸Linux命令行,有一个npm package正是这一点做的。

1

我不知道如何在不打开文件的情况下阅读文件内容进行更改,更改需要更改的内容然后重新写入。 Node中这样做的最有效和高效的方式是通过流,因为您不需要一次读取整个文件。假设你需要编辑的文件有一个新行或回车符,你可以使用Readline模块逐行回答问题文件,并检查该行是否包含你想改变的文本。然后,您可以将该数据写入旧文本所在的文件。

如果您没有换行符,您可以选择使用Transform Stream并检查每个块的匹配文本,但这可能需要将多个块拼接在一起以识别要替换的文本。

我知道你不想或多或少地将文件复制到所做的更改中,但我无法想出另一种效率更高的方法。

const fs = require('fs') 
const readline = require('readline') 

const outputFile = fs.createWriteStream('./output-file.txt') 
const rl = readline.createInterface({ 
    input: fs.createReadStream('./input-file.txt') 
}) 

// Handle any error that occurs on the write stream 
outputFile.on('err', err => { 
    // handle error 
    console.log(err) 
}) 

// Once done writing, rename the output to be the input file name 
outputFile.on('close',() => { 
    console.log('done writing') 

    fs.rename('./output-file.txt', './input-file.txt', err => { 
     if (err) { 
      // handle error 
      console.log(err) 
     } else { 
      console.log('renamed file') 
     } 
    }) 
}) 

// Read the file and replace any text that matches 
rl.on('line', line => { 
    let text = line 
    // Do some evaluation to determine if the text matches 
    if (text.includes('replace this text')) { 
     // Replace current line text with new text 
     text = 'the text has been replaced' 
    } 
    // write text to the output file stream with new line character 
    outputFile.write(`${text}\n`) 
}) 

// Done reading the input, call end() on the write stream 
rl.on('close',() => { 
    outputFile.end() 
}) 
+1

好吧,它结束了类似于你的建议,找不到更好的东西。 谢谢 – jalal246