Siddhartha Chowdhury
Siddhartha Chowdhury

Reputation: 2734

How to delete a file in Sails.js?

Hello guys am new to Sails.js, here I have files created in following structure

--.tmp
   /--public
      /--dir1
         /--dir2
            /--avatar.jpg
            /--banner.jpg

I want solution for

Case:1 - DELETE only avatar.jpg

Case:2 - DELETE all existing images along with the directory "dir2 "

I have tried :

In controller

var fs = require('fs'); fs.unlink(path_to_file) But unfortunately could not make the filepath right.

Please help me out any possible solutions for the above two problem cases.

Thanks in advance

Upvotes: 1

Views: 766

Answers (1)

Daniel
Daniel

Reputation: 18692

For second case:

deleteFolderRecursive = (path) ->
  if fs.existsSync(path)
    fs.readdirSync(path).forEach (file,index) ->
      curPath = path + "/" + file
      if fs.lstatSync(curPath).isDirectory()
        deleteFolderRecursive curPath
      else
        fs.unlinkSync curPath
    fs.rmdirSync path

dir = './tmp/public/dir1/dir2'
deleteFolderRecursive dir

Alternatively you can try changing directory to:

let dir = __dirname + '/tmp/public/dir1/dir2';

Or you can also try to add few /.. before /tmp until your code works and deletes files correctly.

Upvotes: 1

Related Questions