如何在node.js上移动文件(如mv命令shell) ?是否有任何方法,或者我应该读取一个文件,写到一个新文件,并删除旧文件?


当前回答

在下面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 *********/

其他回答

根据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)。除了可能的异常,没有参数 赋给完成回调函数。

使用mv节点模块,它将首先尝试执行fs。重命名,然后退回到复制,然后取消链接。

这是对teoman shipahi的回答的重新讨论,使用了一个稍微不那么模糊的名称,并遵循了在尝试调用代码之前定义代码的设计原则。(虽然node允许您做其他事情,但本末倒置并不是一个好的实践。)

function rename_or_copy_and_delete (oldPath, newPath, callback) {

    function copy_and_delete () {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', callback);
        writeStream.on('error', callback);
        readStream.on('close', 
              function () {
                fs.unlink(oldPath, callback);
              }
        );

        readStream.pipe(writeStream);
    }

    fs.rename(oldPath, newPath, 
        function (err) {
          if (err) {
              if (err.code === 'EXDEV') {
                  copy_and_delete();
              } else {
                  callback(err);
              }
              return;// << both cases (err/copy_and_delete)
          }
          callback();
        }
    );
}

fs。Rename在同步版本中也可用:

fs.renameSync(oldPath, newPath)

对于8.0.0以上的Node版本使用承诺:

const {promisify} = require('util');
const fs = require('fs');
const {join} = require('path');
const mv = promisify(fs.rename);

const moveThem = async () => {
  // Move file ./bar/foo.js to ./baz/qux.js
  const original = join(__dirname, 'bar/foo.js');
  const target = join(__dirname, 'baz/qux.js'); 
  await mv(original, target);
}

moveThem();