【问题标题】:fs: replace file contents by another file contentfs:用另一个文件内容替换文件内容
【发布时间】:2017-05-25 10:10:16
【问题描述】:

给定以下文件:

主机

127.0.0.1 localhost

项目-a.hosts

127.0.0.1 project-a

项目-b.hosts

127.0.0.1 project-b

通过 Node 中的 FS 将主机文件内容替换为另一个给定文件的最简单方法是什么?

【问题讨论】:

    标签: node.js file filesystems fs


    【解决方案1】:

    您可以使用 node.js 中的 fs 模块来执行此操作。这里有两种方法,一种使用异步函数,另一种使用它们的同步模拟。 这很简单。

    我强烈建议您在提问之前更彻底地搜索 StackOverflow,因为这类问题非常常见。以this answer 为例...

    const fs = require('fs');
    
    // async
    function replaceContents(file, replacement, cb) {
    
      fs.readFile(replacement, (err, contents) => {
        if (err) return cb(err);
        fs.writeFile(file, contents, cb);
      });
    
    }
    
    // replace contents of file 'b' with contents of 'a'
    // print 'done' when done
    replaceContents('b', 'a', err => {
      if (err) {
        // handle errors here
        throw err;
      }
      console.log('done');
    });
    
    
    // sync - not recommended
    
    function replaceContentsSync(file, replacement) {
    
      var contents = fs.readFileSync(replacement);
      fs.writeFileSync(file, contents);
    
    }
    
    replaceContentsSync('a', 'b');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多