【问题标题】:Reading a file line by line and based on it write newlines to same file - nodejs逐行读取文件并基于它将换行符写入同一文件 - nodejs
【发布时间】:2016-11-25 06:00:48
【问题描述】:

如果每一行都满足某些条件,我需要逐行读取文件并在读取时将换行符写入同一个文件。最好的方法是什么。

【问题讨论】:

    标签: node.js file-io file-handling


    【解决方案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();
            })
        })
    }
    

    【讨论】:

      【解决方案2】:

      在 fs 的帮助下使用 node fs 模块,您可以异步执行操作,也可以同步执行操作。下面以异步为例

      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');
                  });
              });
      }
      

      同步示例

      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');
              });
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 1970-01-01
        • 2019-01-29
        相关资源
        最近更新 更多