如何在 Node.js 中复制文件?
Node.js 是一个开源和跨平台的运行时环境,用于在浏览器之外执行 JavaScript 代码。 Node.js 运行在各种平台上,例如 Windows、Linux、Mac OS。
Node.js 中使用了多种方法,例如 readFile() 和 writeFile() 方法。 readFile() 和 writeFile() 方法用于将文件的内容复制到另一个文件。
解释:
- readFile(file[,option],callback )
- file: Source filename path.
- option: It has to encode i.e. utf8.
- callback: The callback gets two arguments.
- writeFile(filename, data,encoding, callback)
- filename: Filepath of the file to read.
- data: It is the data that we want to write.
- encoding: It is the encoding of the data.
- callback: It will show the error or null.
执行
Javascript
var fs=require('fs'); // Import the filesystem module
console.log('File Reading from file.txt ..........');
// ReadFile method is used to read the content from file.txt
fs.readFile('file.txt','utf8',readingFile);
function readingFile(error,data)
{
if(error){
console.log(error);
} else
{
console.log(data); // Printing the file.txt file's content
// Creating new file - paste.txt with file.txt's content
fs.writeFile('paste.txt',data,'utf8',writeFile);
}
}
function writeFile(error)
{
if(error){
console.log(error)
} else {
console.log('Content has been pasted to paste.txt file');
}
}