综合编程

Copying file in node.js build script

微信扫一扫,分享到朋友圈

Copying file in node.js build script
0 0

Im playing around with a javascript project, it uses a node build script.

It syncing some folders into a built folder via

try {
  fs.statSync('built/imgs');
} catch(err) {
  if (err.code=='ENOENT') fs.symlinkSync('../imgs', 'built/imgs');
  else throw err;
}

Whats the corresponding fs command to get a real copy of the files to the built folder?

Problem courtesy of: Denny Mueller

Solution

There is no function in the fs
object that will copy a whole directory. There's not even one that will copy a whole file.

However, this is a quick and easy way to copy one file.

var fs = require('fs');

fs.createReadStream('input_filename').pipe(fs.createWriteStream('output_filename'));

Now you just need to get a directory list. You would use the fs.readdir
or fs.readdirSync
for that.

So to copy a directory to another you might do something like this:

var dir = fs.readdirSync('.');
for (var i=0; i < dir.length; i++) {
    fs.createReadStream(dir[i]).pipe(fs.createWriteStream("newpath/"+dir[i]));
}

Solution courtesy of: Daniel

Node.js Recipes
感谢您的支持!

    Software prefetching in C/C++

    上一篇

    著名分析师Ben Thompson:从Spotify进军播客,谈音乐流媒体如何转型

    下一篇

    您也可能喜欢

    评论已经被关闭。

    插入图片

    热门分类