如何在node.js上移动文件(如mv命令shell) ?是否有任何方法,或者我应该读取一个文件,写到一个新文件,并删除旧文件?
当前回答
使用rename函数:
fs.rename(getFileName, __dirname + '/new_folder/' + getFileName);
在哪里
getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName
假设您希望保持文件名不变。
其他回答
下面是一个使用util的例子。我如何移动文件a到不同的分区或设备在Node.js?
var fs = require('fs'),
util = require('util');
var is = fs.createReadStream('source_file')
var os = fs.createWriteStream('destination_file');
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
根据seppo0010的注释,我使用了重命名函数来完成此操作。
http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback
fs。重命名(oldPath, newPath, callback) 新增于:v0.0.2 oldPath <String> | <Buffer> newPath <String> | <Buffer> . newPath <String> 回调函数> < 异步重命名(2)。除了可能的异常,没有参数 赋给完成回调函数。
节点.js v10.0.0+
const fs = require('fs')
const { promisify } = require('util')
const pipeline = promisify(require('stream').pipeline)
await pipeline(
fs.createReadStream('source/file/path'),
fs.createWriteStream('destination/file/path')
).catch(err => {
// error handling
})
fs.unlink('source/file/path')
在下面URL的帮助下,您可以复制或移动您的文件CURRENT Source到Destination Source
https://coursesweb.net/nodejs/move-copy-file
/*********Moves the $file to $dir2 Start *********/ var moveFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var dest = path.resolve(dir2, f); fs.rename(file, dest, (err)=>{ if(err) throw err; else console.log('Successfully moved'); }); }; //move file1.htm from 'test/' to 'test/dir_1/' moveFile('./test/file1.htm', './test/dir_1/'); /*********Moves the $file to $dir2 END *********/ /*********copy the $file to $dir2 Start *********/ var copyFile = (file, dir2)=>{ //include the fs, path modules var fs = require('fs'); var path = require('path'); //gets file name and adds it to dir2 var f = path.basename(file); var source = fs.createReadStream(file); var dest = fs.createWriteStream(path.resolve(dir2, f)); source.pipe(dest); source.on('end', function() { console.log('Succesfully copied'); }); source.on('error', function(err) { console.log(err); }); }; //example, copy file1.htm from 'test/dir_1/' to 'test/' copyFile('./test/dir_1/file1.htm', './test/'); /*********copy the $file to $dir2 END *********/
使用mv节点模块,它将首先尝试执行fs。重命名,然后退回到复制,然后取消链接。
推荐文章
- AngularJS只适用于单页应用程序吗?
- __FILE__宏显示完整路径
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理