fs:用另一个文件内容替换文件内容

dan*_*tes 5 filesystems file fs node.js

给定以下文件:

主机

127.0.0.1 localhost
Run Code Online (Sandbox Code Playgroud)

项目-a.hosts

127.0.0.1 project-a
Run Code Online (Sandbox Code Playgroud)

项目-b.hosts

127.0.0.1 project-b
Run Code Online (Sandbox Code Playgroud)

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

mkh*_*yan 7

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

我强烈建议您在提问之前更彻底地搜索 StackOverflow,因为此类问题非常常见。例如,看看这个答案......

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');
Run Code Online (Sandbox Code Playgroud)