Would like to write data into specific folder using writefile in node js.
I have seen couple of questions in stackoverflow regarding this but none of them worked for me .
For example :
fs.writeFile('./niktoResults/result.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Results Received');
});
This throws an error "NO SUCH FILE OR DIRECTORY"
Is there any alternative for writing data into specific folder node js ???
Ensure that the directory is available & accessible in the working directory.
In this case, a function like below needs to be called at the start of the application.
function initialize() {
const exists = fs.existsSync('./niktoResults');
if(exists === true) {
return;
}
fs.mkdirSync('./niktoResults')
}
Error caused by directory not existing, create a directory if it does not exist.
function create(text, directory, filename)
{
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
console.log('Directory created');
create(text, directory);
} else {
fs.writeFile(`${directory}/${filename}`, `${text}`, function (error) {
if (error) {
throw error;
} else {
console.log('File created');
}
});
}
}
create('Text', 'directory', 'filename.txt');
Related
I want zip a folder which contains few files. I am using zip-folder and 7zip-min modules they are working fine. But, I would like to add some parameters to it, like compression level and directory size and so on.
If it is not possible with this module, Can anyone provide other suggestions?
Here is my code :
Example 1-
const zipFolder = require('zip-folder');
zipFolder('./folder', './compressed.zip', function(err) {
if(err) {
console.log('something went wrong!', err);
} else {
console.log('done with compressing');
}
});
Example 2-
const _7z = require('7zip-min');
let pack = _7z.pack('./folder', './compressed.7z', err => {
console.log('I am done with compressing')
});
I'm having issues with a function that reads a text file line by line. It says the file I'm trying to read does not exist, although it does in the file path I am running node on. What could be the issue??
function insertUsers(auth) {
fs.readFile('emails.txt', function (err, data) {
if (err) throw err;
var person = data.toString().split("\n");
var person = data.toString().split("\n");
for (var i = 0; i < person.length(); i++) {
service.members.insert({
groupKey: 'testgroup#x.com',
resource: {
email: person[i],
role: 'MEMBER',
}
}, (err, res) => {
if (err) { return console.error('The API returned an error:', err.message); }
const user = res.data.member;
if (member.length) {
write_log('Inserted' + email + ' into student group.');
} else {
write_log('Failed to delete ' + email);
}
});
}
});
}
https://i.stack.imgur.com/5UTK6.png and https://i.stack.imgur.com/iVvnA.png
Verify that you're starting your node application from the same location where your file (emails.txt) is. According to your method logic it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups > node main.js
you can check the current working directory from the code
console.log(process.cwd())
it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups
Otherwise, modify your code to correctly point to the email.txt or start your application from the correct directory.
This problem was due to how I made emails.txt. The name is "emails.txt", and the file extension is .txt. I changed the file name to "emails", and it worked.
So my project structure looks like:
root
app.js
node_modules
package.json
Spreadsheets
I want to use the zip-folder module to zip the contents of the folder spreadsheets. The code provided is:
var zipFolder = require('zip-folder');
zipFolder('/path/to/the/folder', '/path/to/archive.zip', function(err) {
if(err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
My code is:
zipFolder('./Spreadsheets/', './', function(err) {
if (err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
because I want to save the zip in the root folder. However I get the following error:
Error: EISDIR: illegal operation on a directory, open './'
at Error (native)
I believe this has something to do with paths but am not sure how to proceed.
You missed zip file name. Working code looks like this:
zipFolder('./Spreadsheets/', './Spreadsheets.zip', function(err) {
if (err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
PS Welcome to Stack Overflow!
This should be a fairly simple one to answer I would hope, however it's got me stumped - maybe I've been staring at too much code today!
I am trying to do a simple if statement which checks to see if a folder exists. If the folder doesn't exist, make it, if it does, delete the content.
The problem I am having is that if the directory doesn't exist, then the callback (stats) is undefined. With fs.exist it would be quite simple, but since its deprecated, I wanted to ensure this was future proofed.
var seriesid = 5;
fs.stat("temp/" + seriesid, function (err, stats){
if(!stats.isDirectory()){
fs.mkdir("temp/" + seriesid);
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
callback();
}
else if (err != 'ENOENT') {
callback(err);
}
else {
// TODO: Folder exists, delete contents
console.log('Does exist');
callback();
}
});
Any help on how to accomplish this would be appreciated
Check err first. Then check isDirectory()
fs.stat("temp/" + seriesid, function (err, stats){
if (err) {
// Directory doesn't exist or something.
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
return fs.mkdir("temp/" + seriesid, callback);
}
if (!stats.isDirectory()) {
// This isn't a directory!
callback(new Error('temp is not a directory!'));
} else {
console.log('Does exist');
callback();
}
});
you need to check if stats exist before doing !stats.isDirectory()
fs.exists is now deprecated for a decent reason that I should try to open a file and catch error to be sure nothing is possible to delete the file in between checking and opening. But if I need to create a new file instead of opening an existing file, how do I guarantee that there is no file before I try to create it?
You can't. You can however, create a new file or open an existing one if it exists:
fs.open("/path", "a+", function(err, data){ // open for reading and appending
if(err) return handleError(err);
// work with file here, if file does not exist it will be created
});
Alternatively, open it with "ax+" which will error if it already exists, letting you handle the error.
module.exports = fs.existsSync || function existsSync(filePath){
try{
fs.statSync(filePath);
}catch(err){
if(err.code == 'ENOENT') return false;
}
return true;
};
https://gist.github.com/FGRibreau/3323836
https://stackoverflow.com/a/31545073/2435443
fs = require('fs') ;
var path = 'sth' ;
fs.stat(path, function(err, stat) {
if (err) {
if ('ENOENT' == err.code) {
//file did'nt exist so for example send 404 to client
} else {
//it is a server error so for example send 500 to client
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );