This article will talk about the fs file system module and introduce the file reading and writing operations innode. I hope it will be helpful to everyone!
##What is fs file system module
fs module is a module officially provided by node.js for operating files. Reading and writing operations on files can be achieved through the fs module. [Related tutorial recommendations:nodejs video tutorial,Programming teaching]
For example:const fs = require('fs');
Read the contents of the specified file
test. txtdocument, and the content inside is:
12341234
// 引入fs模块 const fs = require('fs'); // 读取文件 fs.readFile('./test.txt','utf-8',function(err,data){ console.log(err);// null console.log(data);// 12341234 })
Write content to the specified file
const fs = require('fs'); fs.writeFile('text.txt', '海绵宝宝', 'utf-8', function(err) { console.log(err);// null })
nullwill be output. Is that right? Does it mean that the writing has been successful?
text.txtfile has been generated. Open it and find that the
SpongeBob SquarePants# we just wrote is official. ##.So if we execute the code again and only the written content changes, what will be the result?
fs.writeFile('text.txt', '派大星', 'utf-8', function(err) { console.log(err);// null })
At this time, we open the
text.txtfile again and find that the content inside becomesPat Star
, which means usingwirteFile()
will overwrite the original content of the file.At this time, we can also judge whether the file is written successfully based on the value returned by the parameter of the write file callback function: if null is returned, it means the file is written successfully; otherwise, the writing fails.
EndThrough the fs module of
node.js, we can read and write files Come on, this article is my study notes for learning node.js. If there are any shortcomings, I hope the experts can give me advice.For more node-related knowledge, please visit:
The above is the detailed content of An article to talk about the reading and writing operations of node files. For more information, please follow other related articles on the PHP Chinese website!