Basic concepts
- Fs.exists has been deprecated, you can use fs.access to determine whether the folder exists, but the official recommendation is not to use the fs.access before the file operation, the official recommended way is directly file operation, there are errors and then modify
It is not recommended to use Fs.access () to check the accessibility of a file before calling Fs.open (), Fs.readfile (), or fs.writefile (). This processing can cause a disturbance, as other processes may change the state of the file between two calls. As an alternative, the user code should open/read/write the file directly, and then handle the error when the file is inaccessible.
Basic use
- Fs.writefile callback function If there are errors will be activated
- Fs.mkdirsync callback function No error will not be activated
Const FS = require ("FS"); Const path= Require ("path"); Const moment= Require ("moment"); Const Driarr=[];const year= Moment (). Format ("YYYY");d Riarr.push (year), const month= Moment (). Format ("MM");d Riarr.push (month), const Day= Moment (). Format ("DD");d Riarr.push (day), const TXT= "Helloworld123"; Const Txtname= "Msg1.txt"; let Pathurl= ""; let index= 0;functionMk_dir () {if(Index > Driarr.length-1)return; Pathurl+ = ' ${driarr[index]}/';Console.log (Pathurl); Console.log (index); Try{Index++; Fs.mkdirsync (Pathurl); } Catch(err) {if(Err.code = = = "Eexist") {mk_dir (); } }}functionWr_file () {fs.writefile (' ${year}/${month}/${day}/${txtname} ', txt, error = {if(!error)return; if(Error.code = = = "ENOENT") { for(Let i = 0; i < driarr.length; i++) {mk_dir (); }} wr_file (); });} Wr_file ();
nodejs--Avoid judging create multi-level catalogs