node.js mkdir enonent when passed a string - node.js

I'm trying to build folders with a string, but I keep erroring out, everything looks good, but I'm obviously missing something, any help would be great.
var setFile = 'dijit/analysis/images/'
folders = setFile.substr(0,setFile.lastIndexOf('/'));
fs.mkdir(folders, function(err){
console.log('problem: ' + err);
});
Error: Error: ENOENT, mkdir 'dijit/analysis/images'
Thanks,

fs.mkdir can able to built only a single folder. You are trying to create a folder inside a non existing folder. This problem can be solved by fs-extra module of npm. Following code should fulfill your need.
var setFile = 'dijit/analysis/images/',
fsExtra = require('fs-extra'),
folders = setFile.substr(0, setFile.lastIndexOf('/'));
fsExtra.mkdirp(folders, function(err) {
console.log('problem: ' + err);
});

Kundu's comment answers this problem, but if you want a different solution there is plenty over at How to create full path with node's fs.mkdirSync?

Related

creating multi sub directories in nodejs

I want to check if a directory not exist in my project, make two directories in my nodejs web api project. I use the following code and it works.
const myVar= req.body["specificId"];
const checkPath = path.join(__dirname , "../public/media/" + myVar);
console.log(checkPath);
if (!fs.existsSync(checkPath)) {
console.log("not exist!");
fs.mkdirSync(`${__dirname}../../public/media/`);
fs.mkdirSync(`${__dirname}../../public/media/${myVar}`);
fs.mkdirSync(`${__dirname}../../public/media/${myVar}/image`);
fs.mkdirSync(`${__dirname}../../public/media/${myVar}/video`);
}
else{
console.log("exist!");
}
but as you see I write 4 lines to do so. How may do it just by using something like the two last lines? I should mention that for the first run, just the specified 'public' folder exists and the other sub folders should be created if ${myVar} folder not existed.

Can't find the file I created by fs.writeFile

I am trying to write a file in node.js using fs.writeFile, I use the following code:
const fs = require('filer');
const jsonString = JSON.stringify(myObj)
fs.writeFile('/myFile.txt', jsonString, function (err) {
if (err) throw err;
console.log('Saved!');
});
}
I am sure the file is created, because I can read it by fs.readFile referring to the same address, but I cannot find it on the disk by using windows search. What I understood, if I change the localhost port it saves the files in another location. I already tried "process.cwd()", but it didn't work.
I really appreciate it if someone could help.
try to use : __dirname instead of process.cwd()
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, '/myFile.txt');
console.log(filePath);
const jsonString = JSON.stringify({ name: "kalo" })
fs.writeFile(filePath, jsonString, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
And I would like to know why are you using 'filer' instead of default fs module?
fs module is native module that provides file handling in node js. so you don't need to install it specifically. This code perfectly worked and it prints absolute location of the file as well.Just run this code if it doesn't work, I think you should re install node js. I have updated the answer.You can also use fs.writeFileSync method as well.
From documentation: "String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by calling process.cwd()."
So in order to determine your working directory (i.e. where fs create files by default) call (works for me):
console.log(process.cwd());
Then if you would like to change your working directory, you can call (works for me as well):
process.chdir('path_to_new_directory');
Path can be relative or absolute.
This is also from documentation: "The process.chdir() method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist)."

Should I hard code references to my node_modules folder?

I'm creating an npm package called ctgen and I need to reference a folder within that package. Should I hard code the reference to that folder?
e.g. src = './node_modules/ctgen/scaffold'
or is there a pre-made function that will do this for me?
For a bit more clarity on my issue. I have the following function in my package:
var createFile = function (fileName, componentName, doc) {
// Tell the user what is happening
console.log(chalk.blue('\nCreating', fileName, '...'))
// Bring in the scaffold files (note this should point to the scaffold folder in node modules/ctgen)
var scaffold = './scaffold/' + fileName
fs.readFile(scaffold, 'utf8', function (err, data) {
if (err) return console.log(chalk.red(err))
var result = data.replace(/%cname%/g, componentName)
if (doc) {
var d = new Date()
result = result.replace(/%cfname%/g, doc.componentName)
result = result.replace(/%cdesc%/g, doc.componentDesc)
result = result.replace(/%cauthor%/g, doc.userName)
result = result.replace(/%cagithub%/g, doc.userGithub)
result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
}
fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
if (err) return console.log(chalk.red(err))
console.log(chalk.green(fileName, 'created!'))
})
})
}
It looks in a folder called scaffold for the following files:
view.php
style.styl
component.json
It then pulls the file into a cache, performs a find and replace on some strings and then writes the output to a file in the users project.
It seems though that whenever I try to reference the 'scaffold' folder, it's trying to find it in the users project folder and not in my package folder.
I'm very hesitant to reference the scaffold folder by writing '/node_modules/ctgen/scaffold' as that seems like the wrong thing to do to me.
What you want is __dirname.
If I understand your question, you have a ressource folder contained in your module, and have trouble accessing it since the current path is the path of the app, not your module.
__dirname will contain the path of your script file, and so will point to your module file.
I presume your module is named ctgen, and the files you want to access are in ctgen/scaffold. So in your code, try to access __dirname/scaffold.
In short NO. If you want to read more about how node looks for required files pleas read this: https://nodejs.org/dist/latest-v7.x/docs/api/modules.html#modules_addenda_package_manager_tips
if you are creating an npm package, specify your dependent npm modules within your package.json and use them as intended in node (with require('your-dependent-module-name')). After you published your module and someone npm install --save your-module, it will also install your dependencies into [usrDir]/node_modules/[your-module]/node_modules, where your module will find what it needs.
That beeing said; yes, you could reference __dirname + 'node_modules/[something] but that wouldn't be smart as it makes assumptions how the user is using your module. At the same time, node+npm solves this problem for you, so there is no reason for you to want to do this)

Electron app createWriteStream throwing ENOENT error

I'm trying to download files to the filesystem in an electron app. My code, in the main thread, looks like this:
const dir = `${__dirname}/media`;
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
const file = fs.createWriteStream(`${dir}/${name}`);
file.on("open", function() {
const request = http.get(url, function(response) {
response.pipe(file);
response.on('end', function() {
file.close();
...
});
});
request.on('error', function(err) {
...
});
});
This works when running in development using electron . But after I build it with electron-builder, I get the error in an alert:
Uncaught Exception:
Error: ENOENT, media/uploads_2016_02_BASF_Holistic_Program.jpg not found in /Users/nicholasstephan/Desktop/XXXXXXX/dist/Mac/XXXXXX.app/Contents/Resources/app.asar
at notFoundError (ELECTRON_ASAR.js:109:19)
at Object.module.(anonymous function) [as open] (ELECTRON_ASAR.js:209:16)
at WriteStream.open (fs.js:1890:6)
at new WriteStream (fs.js:1876:10)
at Object.fs.createWriteStream (fs.js:1831:10)
at next (/Users/nicholasstephan/Desktop/XXXXXXXX/dist/Mac/XXXXXXXX.app/Contents/Resources/app.asar/media.js:19:18)
at /Users/nicholasstephan/Desktop/XXXXXXXX/dist/Mac/XXXXXXXX.app/Contents/Resources/app.asar/media.js:52:4
...
where the media.js, ln 19, being referred to is the const file = fs.createWriteStream(${dir}/${name}); line in the code.
I've tried the solutions offered in about a dozen other similar stackoverflow answers, but none have fixed the problem.
What's going on here?
Thanks.
The built Electron app uses the Asar format. Asar is an archive format (it's really just one big file) though in Electron you are able to read from it as if it were a standard directory.
I presume (though I have not seen it explicitly documented) that it is not possible to write to an Asar with the fs functions. In any case there are almost certainly more appropriate locations to write data.
Try writing to a different path. Electron provides a number of useful paths using app.getPath(name) so you could for example write to the userData directory which holds configuration files for your app.

How to create folder hierarchy of year -> month -> date if not exist in node.js

I am trying to create folder hierarchy named current year inside create another folder with name current month and then again inside that folder create another folder with name current date.
For example : Today's date is 2016-05-02, So the folder should be create if not already exist like following structure
2016->05->02
See this previously answered question
Good way to do this is to use mkdirp module.
$ npm install mkdirp
Then use it to run function that requires the directory. Callback is called after path is created (if it didn't already exists). Error is set if mkdirp failed to create directory path.
var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) {
// path was created unless there was error
});
The best solution would be to use the npm module called node-fs-extra. The main advantage is that its built on top of the module fs, so you can have all the methods available in fs as well. It has a method called mkdir which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically. The module is a super set of npm module fs, so you can use all the functions in fs also if you add this module.
one example
var fse = require('fs-extra')
var os = require('os')
function getTempPath() {
return os.tmpdir();
}
mymodule.get('/makefolder',function(req,res){
var tempfolder = getTempPath();
var myfolder = tempfolder + '/yearfolder/monthfolder/datefolder/anyotherfolder';
fse.mkdirs(myfolder, function (err) {
if (err) return res.json(err)
console.log("success!")
res.json("Hurray ! Folder created ! Now, Upvote the solution :) ");
})
});

Resources