fs rename file nodejs code example

Example 1: fs renaming files

const fs = require("fs")

fs.rename("./testfile.txt", "./newtestfile.txt", (err) => {
	if (err) console.log(err)
})

Example 2: nodejs readfile

const fs = require('fs');

fs.readFile('/Users/joe/test.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err);
    return
  }
  console.log(data);
});

Example 3: fs.readfile

fs.readFile('filename', function read(err, data) {
    if (err) {
        throw err;
    }
    var content = data;
  
    console.log(content);  
   
});

Example 4: rename a file using node.js

const { join } = require('path');
const { readdirSync, renameSync } = require('fs');
const [dir, search, replace] = process.argv.slice(2);
const match = RegExp(search, 'g');
const files = readdirSync(dir);

files
  .filter(file => file.match(match))
  .forEach(file => {
    const filePath = join(dir, file);
    const newFilePath = join(dir, file.replace(match, replace));

    renameSync(filePath, newFilePath);
  });

// Usage
// node rename.js path/to/directory 'string-to-search' 'string-to-replace'