Article From:https://www.cnblogs.com/kerbside/p/9378584.html

Contents

Node file operation”

In actual development, there are many operations about files and folders, such as creating, deleting files and folders, copying, compressing and producing word. File systems, stream operations, and related dependencies are used to encapsulate some commonly used methods for reuse.

fs file system”

File operation is a very common way, the following outline of synchronous and asynchronous operation methods, file flow operations need to be monitored through pipeline communication, specific events can be referred to: monitoring events.

// Citing file systemConst FS = require ('fs');/ / the longest problems encountered in file operation: synchronous and asynchronous operations/ / file read asynchronous operationFs.readFile ('/etc/passwd', (ERR),Data) => {/ / callback functionIf (ERR) throw err;Console.log (data);});/ / file read synchronization operationFs.readFilESync ('< directory> ');/ / file flow operationFs.createReadStream ('sample.txt', {encoding:'utf-8'});Fs.creAteWriteStream ('sample.txt'), {close: false}).On ('close', function () {/ / monitor close events to achieve synchronous operation of file stream transmission...})/ / copy files from A to B through file streamsFs.createReadStream ('/A/sample.txt', {encoding:'utf-8'}).Pipe (fs.crea)TeWriteStream ('/B/sample.txt'), {close: false}).On ('close', function () {/ / monitor close events to synchronize file stream transmissionoperation...});

officegen Office plug-in”

Export word depends on officegen package and git address. A detailed description of the ways in which API is used is, of course, asynchronous.

// Introducing officegenConst officegen = require ('officegen');/ / create ppt 2007:Var pptx = officegen ('pptx'));/ / create Word 2007:Var docx = officegen ('docx');/ / create Excel 2007:Var xlsx = officegen ('xls)X');/ / create ppt as an examplePptx.setDocTitle ('< title> ');Var out = fs.createWriteStream ('out.pptx')) / / stream output to create files.Pptx.generate (out);Out.on ('close', function () {Console.log ('Finished)To create the PPTX file!) / / callback performs the next steps to achieve synchronous operation.});

file operation

Recursively create folders with no duplicate names. FilePath is a folder path. Num is the initial state 0.


/**
 * create folder* @param * * * filePath* @param * * * num* * /Function mkDifDir (filePath, Num) {Var newFIlePath = filePath;While (fs.existsSync (newFilePath) & & fs.statSync (newFilePath).IsDireCtory ()) {Num++;NewFilePath = filePath + '(' + num + ').}Fs.mkdirSync (NE)WFilePath);Return newFilePath;}/ / way of invocationMkDifDir ('D://abc', 0);/ / return result/ / if there is a ABC folder in the destination directory, createABC (1) folder, return D://abc (1), otherwise create ABC folder directly.// If there is still an ABC (1) folder, then analogize until the ABC (n) folder location is not created repeatedly and the value is returned

Create folders recursively based on incoming multiple and directory recursion

/**
 * Create multilayer directory files* @param * * * dirname* * /Function mkdirsSync (dirname) {If (fs.existsSync (dirname)) {Return true;} else {If (mkdirsSync (path.dirname (dirname))) {Fs.mKdirSync (dirname);Return true;}}}/ / way of invocationMkdirsSync ('D://a//b//c//d//e/)/f');/ / return result/ / will generate a==>, b==> c==> d==> e==> F file structure folder in D disk./ / if D://a//b//c//d exists, e will be created under D.==> F file structure folder

The advanced version of the above method is also called the above method, and then nested a layer, you can directly create a directory folder and files

/**
 * Create files include folder directory* @param * * * filePath* * /Function createFile (filePath) {Var dirPath = path.dirnaMe (filePath);MkdirsSync (dirPath);If (fs.existsSync (filePath)) {Fs.writeFileSync (FilePath, ', {/ / create fileEncoding:'utf-8'})}}/ / way of invocationMkdirsSync ('D://a//)B//c//d//e//f//abc.txt');/ / return result// will generate a = >, B = >, C = >, d = >, e = = >, f file structure folder in turn, and create it under f folderAcb.txt// If D://a//b//c//d exists, a folder of e==> f file structure is created under d, and a C b.txt is created under f folder.

Delete all files and folders from folder under directory, and also operate recursively.

/**
 * Delete all contents under URL* @param * * * URL* * /Function deleteAllFiles (URL) {Var files = [];Files = FS.readdirSync (URL);If (files.length = = 0) {Fs.rmdirSync (URL);}Files.forEach (f)Unction (file, index) {/ / var curPath = URL + "/" + file;Var curPath = path.join (U)RL, file);//fs.statSync reads folders file synchronously, if it is a folder, repeats trigger function.If (fs.statSync (curPath).IsDirector)Y ()) {/ / recurseDeleteAllFiles (curPath);/ / file delete file} else{Fs.unlinkSync (curPath);}});/ / clear folderFs.rmdirSync (URL);}/ / callertype/ / existing directory/ / D--a--b--c--d--e--f--abc.txt/ / |--h--r--n--abc.txt/ / |--i--t--m--abC.txt/ / |--j--y--k--abc.txt/ / |--k--y--l--abc.txtMkdirsSync ('D://a//b//c');/ / /Only D://a//b//c folders are left, and all internal contents are removed.

office operation”

In fact, the above API has written how to invoke and implement, and the API in the connection is clearer, but when we use it, we often generate a lot of words to write repeatedly each time, so encapsulate a callback method to generate word, other can be expanded according to the specific content. The following are achieved:

/**
 * Import data and generate word.* @param {data imported} data* @param {export path} outPath* @param {back to function} callback* * /FunctIon exportWord (data, outPath, callback) {Var docx = officegen ('docx');Var pObj = docx.creaTeP ();PObj.addText (data);Var out = fs.createWriteStream (outPath, {close: false}); / /File writingOut.on ('error', function (ERR) {Logger.info ("exportWord error! OutPath:" + outPath, ERR);});Docx.generate (out);Out.on ('close', function () {Logger.info ("e")XportWord success! OutPath: "+ outPath";Callback ('callback');});}/ / so there is no need to write repetition.The way of calling is as followsExportWord ('balabalabala...', abc. docx', function ()) {// Export word file abc. docx, word content BalabalaBala...ExportWord ('balabalabala...', qwe. docx', function ()) {// export word file qwe. docx, word content balAbalabala...ExportWord ('balabalabala...),'123.docx', function () {/ / export word file 123.docx,Word content balabalabala.../ / continue other operations in callback....});});});

Post Views: 4

Link of this Article: Nodejs file related operations