mem-fs & mem-fs-editor提供了一系列API,方便操作模板文件(作者也是Inquirer.js的作者)。Yeoman的this.fs就是个mem-fs-editor的一个实例对象,this.fs.copyTpl拷贝模板文件的方法就是mem-fs-editor提供的。
读写文件
read(filepath, [options]):将文件内容作为string返回。options.raw = true可以返回文件原始内容buffer。文件不存在会报错,如果你不想用try-catch,可以设置options.defaults返回默认值,这样就不会报错了。
readJSON(filepath, [defaults]):读JSON
write(filepath, contents):写文件
writeJSON(filepath, contents[, replacer [, space]]):写JSON
const path = require('path'); const memFs = require("mem-fs"); const editor = require("mem-fs-editor"); const store = memFs.create(); const fs = editor.create(store); const srcFile = path.resolve(__dirname, '../tmp/data2.txt'); const srcJson = path.resolve(__dirname, '../../package.json'); const destTpl = path.resolve(__dirname, '../tmp/dataMemFs.tpl'); const destJson = path.resolve(__dirname, '../tmp/dataMemFs.json'); fs.read(srcFile); // hello world! fs.read(srcFile, { raw: true }); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 21> fs.read('somefile.txt', { defaults: '文件不存在' }); // 文件不存在 fs.readJSON(srcJson); // json对象 fs.write(destTpl, "<%= value %%gt;"); fs.writeJSON(destJson, JSON.parse(JSON.stringify({ name: "tool-demo" })));
改删文件
append(filepath, contents, [options]):文件末添加新内容,options.trimEnd默认为true,options.separator新旧内容间的分隔符,默认EOL
extendJSON(filepath, contents[, replacer [, space]]):JSON文件末添加新内容
delete(filepath, [options]):删文件或文件夹
fs.append(destTpl, "<%= value2 %>", { separator: '\r\n----\r\n' }); fs.extendJSON(destJson, JSON.parse(JSON.stringify({ description: "some tool demo" }))); fs.delete(destJson);
拷贝/移动
copy(from, to, [options], context[, templateOptions ]):拷贝文件
copyTpl(from, to, context[, templateOptions [, copyOptions]]):拷贝模板
move(from, to, [options]):移动文件
fs.copy(destTpl, path.join(__dirname, '../tmp/mem-fs/dataMemFs.tpl')); fs.copyTpl(destTpl, path.join(__dirname, '../tmp/mem-fs/dataMemFs.txt'), { value: 1, value2: 2 }); fs.move(path.join(__dirname, '../tmp/mem-fs/dataMemFs.tpl'), destTpl);
其他
exists(filepath):文件是否存在
commit([filters,] callback):将内存中的文件操作全部提交到磁盘上
fs.exists(destTpl); // true fs.commit(() => {}); // 同步 fs.commit(() => { resolve(); }); // 异步