How to delete all pictures of an directory - javascript

I am trying to delete all pictures of an directory. But getting error on directory path. And also dont know how to get all pictures path & delete all of them.
My directory structure :
server
-> app.js
tmp
-upload
-- pic.jpg
-- pic2.jpg
-- pic3.jpg
I have tried this :
var dir = require('../tmp/upload');
var fs = require('fs');
var promise = require('bluebird');
fs.readdir(dir).then(function(file) {
console.log(data)
}).catch(function(err){
console.log
})
But getting error : Cannot find module '../tmp/upload'
Need help to get the path & all pictures on upload folder & delete them.
Thanks in advance

You got this error simply because you actually required a module from the relative path instead of resolving it. In order to resolve a relative path to an absolute path, you need to use path.resolve, not require.
var path = require('path');
var dir = path.resolve('../tmp/upload');

const fsPromises = require('fs').promises
// For ES syntax: import { promises as fsPromises } from 'fs'
const directory = 'your/directory/path/here'
await fsPromises.rmdir(directory, {
recursive: true
})

Related

Cannot find module Error While js files are located in same Directory

I have added a js Module called mongoUtil, which contains the code hereafter, following a suggestion found at this link.
const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://localhost:27017";
var _db;
module.exports = {
connectToServer: function(callback) {
MongoClient.connect(url, {useNewUrlParser: true}, function(err, client) {
_db = client.db('MyDB');
return callback(err);
});
},
getDb: function() {
return _db;
}
};
I have furthermore used the following line in my app.js Module:
const mongoUtil = require('mongoUtil')
However, I am obtaining the following error while the 2 Modules are located in the same Directory:
Error: Cannot find module 'mongoUtil'
What am I missing?
If you provide a module name to require it will search node_modules for it.
If you want to read a module from the current directory, you need to use the file path. This can be relative: require("./mongoUtil")
The exact documentation is here including a (rather long) pseudocode explanation of how the algorithm of locating a module works.
But in short, there are two basic ways of loading a module:
Using the name of an installed module (may be globally or locally installed), for example require('mongodb'). This would look for the (global or local) node_modules/mongodb folder.
Using a path (absolute or relative), for example require('./mongoUtil'). This would look for a file at the given path - if it's relative, then it is relative to the current file.
So, the solution is to use require('./mongoUtil') and not require('mongoUtil').
This will work:
const mongoUtil = require('./mongoUtil.js');
Or even just the following, since the extension is automatically resolved:
const mongoUtil = require('./mongoUtil');

How to access a group of files, regardless of folder name with fs/require

So I have a group of files organized like this:
./main/folder1/files.js
./main/differentfolder/files.js
./main/test/files.js
./main/test/files.js
The files are NOT named files.js, it's my way of saying that there's a lot of files in that folder.
How do I access all the files shown above without doing something like this:
const commandFiles = fs.readdirSync(`./main/folder1/files.js`)
const commandFiles2 = fs.readdirSync(`./main/differentfolder/files.js`)
const commandFiles3 = fs.readdirSync(`./main/test/files.js`)
//and so on
Just grab all the Javascript files inside "main" regardless of the folder name, both using "fs" and "require". I'd expect it to be the same. There is nothing but folders in ./main.
EDIT: I just want it so fs can check /main//files instead of what's inside of main
I easily solved this problem by using the require-all package which was something installed with the other packages I'm using for my app:
const fs = require('fs');
var folders = fs.readdirSync('./main/').filter(n => n !== '.DS_Store') //filter out that disgusting macOS file
folders.forEach(async (folder) => {
var cmdfolder = Object.values(require('require-all')(__dirname + `/main/${folder}`))
cmdfolder.forEach(async (key) => {
var file = require(`./main/${folder}/${key.fileName}`)'
//register file
})
})

Finding the directory portion of a String containing a file name in Node?

Processing a bunch of files using Node and I need to separate the file name from the directory. Does node have a simple way to do this without additional dependencies? I could use an NPM package like Filename Regex, but thought I'd check if there something available out of the box?
So for example suppose we have src/main/css/file.css. Hoping something like this is possible:
const fs = require('fs');
const path = fs.filePath(String pathAndFileName); //path = src/main/css
const file = fs.fileName(String pathAndFileName); //file = file.css
The utilities for manipulating file paths are in the path module.
https://nodejs.org/api/path.html
const {dirname, basename} = require('path');
const path = dirname(String pathAndFileName);
const file = basename(String pathAndFileName);

How do I use "stream.pipe(fs.createWriteStream())"

How do I use stream.pipe?
I'm running a function that outputs:
const fs = require('fs');
const screenshot = require('screenshot-stream');
const stream = screenshot('http://google.com', '1024x768');
stream.pipe(fs.createWriteStream('picture.png'));
My next step is taking that picture (picture.png) and assigning it here:
var content = fs.readFileSync('/path/to/img')
In other words, what is the path to the image so I can upload it?
Lets say, Your project directory name is "PROJECT", And you executed this file from the root directory of your project, Then the PICTURE.png file will be created in the root directory.
And the path to that file'll be __dirname + "/PICTURE.png" if you are still in the root directory of your project.

calling a function in another file in javascript using node.js

I have a problem, i am trying to create an object that i can use over and over in a separate javascript file. I have a file called foo.js and another file called boo.js. I want to create the object in boo.js In my server.js file i required foo.js, and it works fine i can access foo.js. I want to be able to access boo.js from foo.js. I keep getting errors when i require boo.js in foo.js and i cant access it. Is There a way to do this?
here is my code
//boo.js
var obj = function () {
return {
data: 'data'
}
}
module.exports = {
obj: obj
}
foo.js
//foo.js
var request = require('request');
var x = require('./modules/boo')
var random= function() {
return x.obj();
}
module.exports = {
random: random
}
If they are in the same directory you will want to require like so var x = require('./boo'). The ./ is relative to the current directory.
they are both in the same directory
In that case, you'll want to remove the modules/ from the path:
var x = require('./boo');
require() is aware of the current script's location and bases relative paths from the script's own parent directory.
The ./ at the start of the path will refer to the same directory as __dirname, which seems to be modules/.
console.log(__dirname);
// "/project-path/modules"
Including modules/ in the path will result in doubling it:
var path = require('path');
console.log(path.resolve(__dirname, './modules/boo'));
// "/project-path/modules/modules/boo"
(Side note: The fs module does not behave the same way. Relative paths for it are based from the current working directory or process.cwd().)

Categories

Resources