逐行讀取文件並基於它將換行符寫入同一文件 - nodejs (Reading a file line by line and based on it write newlines to same file - nodejs)


問題描述

逐行讀取文件並基於它將換行符寫入同一文件 ‑ nodejs (Reading a file line by line and based on it write newlines to same file ‑ nodejs)

如果每一行都滿足某些條件,我需要逐行讀取文件並在讀取時將換行符寫入同一個文件。最好的方法是什麼。


參考解法

方法 1:

function (file, callback) {
fs.readFile(file, (err, 'utf8', data) => {
if (err) return callback(err);

    var lines = data.split('\n');

    fs.open(file, 'w', (err, fd) => {
        if (err) return callback(err)

        lines.forEach(line => {
            if (line === 'meet your condition') {
                // do your write using fs.write(fd, )
            }
        })
        callback();
    })
})

}
</code></pre>

方法 2:

use node fs module with the help of fs you can perform operation asynchronously as well as synchronously. below is as an example of asynchronously

function readWriteData(savPath, srcPath) {
    fs.readFile(srcPath, 'utf8', function (err, data) {
            if (err) throw err;
            //Do your processing, MD5, send a satellite to the moon or can add conditions , etc.
            fs.writeFile (savPath, data, function(err) {
                if (err) throw err;
                console.log('complete');
            });
        });
}

Synchronously example

function readFileContent(srcPath, callback) { 
    fs.readFile(srcPath, 'utf8', function (err, data) {
        if (err) throw err;
        callback(data);
        }
    );
}

function writeFileContent(savPath, srcPath) { 
    readFileContent(srcPath, function(data) {
        fs.writeFile (savPath, data, function(err) {
            if (err) throw err;
            console.log('complete');
        });
    });
}

(by ShyamSundar RSimonmohan rathour)

參考文件

  1. Reading a file line by line and based on it write newlines to same file ‑ nodejs (CC BY‑SA 2.5/3.0/4.0)

#file-handling #file-io #node.js






相關問題

c語言使用文件操作創建數據庫 (Create database using file operation in c language)

使用jsp瀏覽文件和文件夾 (browsing files and folders using jsp)

在 rails/paperclip 中處理一系列圖像 (handling an array of images in rails/paperclip)

Java 並行文件處理 (Java Parallel File Processing)

Perl 隱式關閉重置 $. 多變的 (Perl implicit close resets the $. variable)

更換和存放 (Replacing and Storing)

逐行讀取文件並基於它將換行符寫入同一文件 - nodejs (Reading a file line by line and based on it write newlines to same file - nodejs)

使用 PHP 將數據放到服務器上(新的 DOMdocument 不起作用) (Use PHP to put data onto server ( new DOMdocument not working))

表示“目錄”或“文件”的詞是什麼? (What is the word that means "directory" or "file"?)

如何在我的計算機上保存我用 Python 編輯的 CSV 文件? (How do I save a CSV file on my computer which i have edited in Python?)

使用文件中的類和對象獲取信息 (Get info using class and object from file)

使用 putw() 時在文件中獲取亂碼 (Getting gibberish values in files when putw() is used)







留言討論