nodejs--Avoid judging create multi-level catalogs

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.