joelanman,
@joelanman@hachyderm.io avatar

missing from native Node - write a file and create any necessary folders in the path

fs.writeFileSync('a/b/c.txt','hello', {recursive:true})  

#nodeJS

joelanman,
@joelanman@hachyderm.io avatar

you can do this, thanks @jscholes

const filepath = 'a/b'  
fs.mkdirSync(filepath, { recursive: true })  
fs.writeFileSync(filepath + '/c.txt', 'hello')  
joelanman,
@joelanman@hachyderm.io avatar
jscholes,
@jscholes@dragonscave.space avatar

@joelanman Do other programming languages/stdlibs offer this? I've seen the equivalent of mkdir -p in many (including Node), but not with a file on the end.

joelanman,
@joelanman@hachyderm.io avatar

@jscholes not sure, but it's such a common need I find. Python has this apparently:

from pathlib import Path

Path("my/path/to/create").mkdir(parents=True, exist_ok=True)  

Also, how do you do that in Node? So that it doesn't complain if it already exists?

jscholes,
@jscholes@dragonscave.space avatar

@joelanman That Python code would make a directory though, not a file. I think it's the equivalent of calling Node's mkdir with recursive: true.

joelanman,
@joelanman@hachyderm.io avatar

@jscholes yup, but Node's errors if it exists, so you have to wrap it in a path check - thats what I meant by complaining

jscholes,
@jscholes@dragonscave.space avatar

@joelanman @joelanman I thought that was the point of recursive? Not only to make the parent dirs, but also to not complain if some part of the path already exists. Which is a terrible API decision if true, and a crappy omission if I'm wrong.

Note that if the error can't be avoided, let it be thrown and then catch it. Don't check for the directory's existance first, and then try to create it if it wasn't found, which introduces the potential for a race condition.

joelanman,
@joelanman@hachyderm.io avatar

@jscholes ah you're right! I was sure it threw an error but recursive: true doesnt, thanks!

  • All
  • Subscribed
  • Moderated
  • Favorites
  • programming
  • kavyap
  • mdbf
  • osvaldo12
  • ethstaker
  • tacticalgear
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • modclub
  • Youngstown
  • everett
  • slotface
  • rosin
  • GTA5RPClips
  • provamag3
  • khanakhh
  • cisconetworking
  • tester
  • ngwrru68w68
  • normalnudes
  • Durango
  • InstantRegret
  • cubers
  • megavids
  • Leos
  • anitta
  • JUstTest
  • lostlight
  • All magazines