This time I will bring you the batch renaming of node files. What are the precautions for batch renaming of node files? The following is a practical case, let’s take a look.
In an actual requirement, a batch of files (such as text, pictures) need to be renamed and numbered according to numbers. I just took this opportunity to get familiar with node's fs file operations and wrote a script to batch modify file names. RequirementsExisting following image filesThere are two ways of synchronous and asynchronous in the fs module
//异步fs.readFile('test.txt', 'utf-8' (err, data) => { if (err) { throw err; } console.log(data); });//同步let data = fs.readFileSync('test.txt');console.log(data);
fs.writeFile('test2.txt', 'this is text', { 'flag': 'w' }, err => { if (err) { throw err; } console.log('saved'); });
flag writing method:
fs.mkdir('dir', (err) => { if (err) { throw err; } console.log('make dir success'); });
fs.readdir('dir',(err, files) => { if (err) { throw err; } console.log(files); });
fs.stat('test.txt', (err, stats)=> { console.log(stats.isFile()); //true})
stats.isFile() 是否为文件 stats.isDirectory() 是否为目录 stats.isBlockDevice() 是否为块设备 stats.isCharacterDevice() 是否为字符设备 stats.isSymbolicLink() 是否为软链接 stats.isFIFO() 是否为UNIX FIFO命令管道 stats.isSocket() 是否为Socket
let stream = fs.createReadStream('test.txt');
let stream = fs.createWriteStreamr('test_copy.txt');
Create a write streamLink the pipe and write the file content
let fs = require('fs'), src = 'src', dist = 'dist', args = process.argv.slice(2), filename = 'image', index = 0;//show helpif (args.length === 0 || args[0].match('--help')) { console.log('--help\n \t-src 文件源\n \t-dist 文件目标\n \t-n 文件名\n \t-i 文件名索引\n'); return false; } args.forEach((item, i) => { if (item.match('-src')) { src = args[i + 1]; } else if (item.match('-dist')) { dist = args[i + 1]; } else if (item.match('-n')) { filename = args[i + 1]; } else if (item.match('-i')) { index = args[i + 1]; } }); fs.readdir(src, (err, files) => { if (err) { console.log(err); } else { fs.exists(dist, exist => { if (exist) { copyFile(files, src, dist, filename, index); } else { fs.mkdir(dist, () => { copyFile(files, src, dist, filename, index); }) } }); } });function copyFile(files, src, dist, filename, index) { files.forEach(n => { let readStream, writeStream, arr = n.split('.'), oldPath = src + '/' + n, newPath = dist + '/' + filename + index + '.' + arr[arr.length - 1]; fs.stat(oldPath, (err, stats) => { if (err) { console.log(err); } else if (stats.isFile()) { readStream = fs.createReadStream(oldPath); writeStream = fs.createWriteStream(newPath); readStream.pipe(writeStream); } }); index++; }) }
Use JS code to create barrage effects
Use H5 canvas to create barrage effects
The above is the detailed content of node file batch rename. For more information, please follow other related articles on the PHP Chinese website!