Dan Heller
Dan Heller

Reputation: 584

fs: replace file contents by another file content

Given the following files:

hosts

127.0.0.1 localhost

project-a.hosts

127.0.0.1 project-a

project-b.hosts

127.0.0.1 project-b

What is the easiest way to replace the hosts file contents by another given file, via FS in Node?

Upvotes: 5

Views: 12229

Answers (1)

mkhanoyan
mkhanoyan

Reputation: 2069

You can do this using the fs module in node.js. Here are two ways of doing it, one using async functions and the other using their sync analogs. This is as simple as it will get.

I would highly recommend you search StackOverflow more thoroughly before asking questions, since this sort of question is extremely common. Check out this answer for example...

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

Upvotes: 8

Related Questions