当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js fs.unlink()用法及代码示例


fs.unlink()方法用于从文件系统中删除文件或符号链接。此函数不适用于目录,因此建议使用fs.rmdir()删除目录。

用法:

fs.unlink( path, callback )

参数:此方法接受上述和以下所述的两个参数:



  • path:它是一个字符串,Buffer或URL,代表必须删除的文件或符号链接。
  • callback:该方法执行时将调用该函数。
    • err:如果方法失败,将抛出此错误。

以下示例说明了Node.js中的fs.unlink()方法:

范例1:本示例从文件系统中删除文件。

// Node.js program to demonstrate the 
// fs.unlink() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Get the files in current diectory 
// before deletion 
getFilesInDirectory(); 
  
// Delete example_file.txt 
fs.unlink("example_file.txt", (err => { 
  if (err) console.log(err); 
  else { 
    console.log("\nDeleted file:example_file.txt"); 
  
    // Get the files in current diectory 
    // after deletion 
    getFilesInDirectory(); 
  } 
})); 
  
// Function to get current filenames 
// in directory with specific extension 
function getFilesInDirectory() { 
  console.log("\nFiles present in directory:"); 
  let files = fs.readdirSync(__dirname); 
  files.forEach(file => { 
    console.log(file); 
  }); 
}

输出:

Files present in directory:
example_file.txt
index.js
package.json

Deleted file:example_file.txt

Files present in directory:
index.js
package.json

范例2:本示例从文件系统中删除符号链接。

// Node.js program to demonstrate the 
// fs.unlink() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Creating symlink to file 
fs.symlinkSync(__dirname + "\\example_file.txt", "symlinkToFile"); 
console.log("\nSymbolic link to example_file.txt created"); 
  
// Function to get current filenames 
// in directory with specific extension 
getFilesInDirectory(); 
  
// Deleting symbolic link to example_file.txt 
// Delete example_file.txt 
fs.unlink("symlinkToFile", (err => { 
  if (err) console.log(err); 
  else { 
    console.log("\nDeleted Symbolic Link:symlinkToFile"); 
  
    // Get the files in current diectory 
    // after deletion 
    getFilesInDirectory(); 
  } 
})); 
  
// Function to get current filenames 
// in directory with specific extension 
function getFilesInDirectory() { 
  console.log("\nFiles present in directory:"); 
  let files = fs.readdirSync(__dirname); 
  files.forEach(file => { 
    console.log(file); 
  }); 
}

输出:

Symbolic link to example_file.txt created

Files present in directory:
example_file.txt
index.js
package.json
symlinkToFile

Deleted Symbolic Link:symlinkToFile

Files present in directory:
example_file.txt
index.js
package.json

参考: https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback




相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | fs.unlink() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。