Node脚本,复制&追加

272 阅读1分钟

背景

在捣鼓项目一些配置的时候,

  1. 需要用到把一个文件复制到另一个文件夹里;
  2. 复制一个文件的内容,追加到另一个文件里

code

  1. copy文件1
const fs = require('fs');
const path = require('path');

const resolvePath = (thePath) => {
  return path.resolve(__dirname, thePath);
};

function moveCopy(orgFilepath, desFilepath) {
    // ... 添加判断文件是否存在,这里为了简便就没写了
  fs.copyFileSync(orgFilepath, desFilepath);
}
moveCopy(resolvePath('../src/global.d.ts'), resolvePath('../lib/index.d.ts'));

  1. copy文件2
const fs = require('fs');
const path = require('path');

const resolvePath = (thePath) => {
  return path.resolve(__dirname, thePath);
};

function moveCopy(orgFilepath, desFilepath) {
  const rs = fs.createReadStream(orgFilepath);
  const ws = fs.createWriteStream(desFilepath);
  fs.pipe(ws);
}
moveCopy(resolvePath('../src/global.d.ts'), resolvePath('../lib/index.d.ts'));
  1. 追加文件内容到新的文件里
#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

const resolvePath = (thePath) => {
  return path.resolve(__dirname, thePath);
};

function moveCopy(orgFilepath, desFilepath) {
  const rs = fs.readFileSync(orgFilepath);
  console.log('rs', rs);
  fs.appendFileSync(desFilepath, rs);
}
moveCopy(resolvePath('../src/global.d.ts'), resolvePath('../lib/index.d.ts'));