Files is deleting before its used in node js - javascript

I'm new to node js and i'm trying to do the following:
function createPasswordfile(content)
{
fs.writeFile(passwordFileName,content, function(err) {
if(err) {
console.log("Failed on creating the file " + err)
}
});
fs.chmodSync(passwordFileName, '400');
}
function deletePasswordFile()
{
fs.chmodSync(passwordFileName, '777');
fs.unlink(passwordFileName,function (err) {
if (err) throw err;
console.log('successfully deleted');
});
}
and there are three statements which call these functions:
createPasswordfile(password)
someOtherFunction() //which needs the created password file
deletePasswordFile()
The problem I'm facing is when I add the deletePasswordFile() method call, I get error like this:
Failed on creating the file Error: EACCES, open 'password.txt'
successfully deleted
Since its non blocking, I guess the deletePasswordFile function deletes the file before other function make use of it.
If deletePasswordFile is commented out, things are working fine.
How should I prevent this?

writeFile is asynchronous, so it's possible the file is still being written when you try and delete it.
Try changing to writeFileSync.
fs.writeFileSync(passwordFileName, content);

Related

Nodejs File get deleted before sending response (res.send)

Here the problem is File get deleted from the server before sending a response to the client and display error as no image on this path.
// Here some code
res.status(200).sendFile(path.join(__dirname, "../../image", `/${response.id}.png`));
// Delete image from server
fs.unlink(imagePath, function (err) {
if (err) throw err;
console.log('File deleted!');
})
You will need to monitor the callback to res.sendFile() so you know when the sending is actually done before you can safely delete your file.
res.sendFile() is asynchronous so it returns before the job is done, thus you were deleting the file before res.sendFile() was done. Use the callback to know when it's actually done.
let fname = path.join(__dirname, "../../image", `/${response.id}.png`);
res.status(200).sendFile(fname, err => {
if (err) {
console.log(err);
res.sendStatus(500);
}
fs.unlink(fname, function(err) => {
// log any error
if (err) {
console.log(err);
}
});
});
Note: When you pass a callback to res.sendFile() you have to manually handle an error condition and send an error response, retry, send alternative content, etc... to send some appropriate response.
I'm also wondering why you're sending one filename and attempting to delete a different one. Wouldn't it make sense to use the same local variable for the filename you're sending and the one you're deleting?

fs.unlink() does not work and callback does not fire

It was working a while ago, and I'm not sure what changed to where the fs.unlink() function seems to be totally skipped. The file for deletion is saved in the root package directory, while the typescript file that contains my code is in the dist folder. It worked when I passed in only the fileName like this: fs.unlink(fileName). But now that doesn't work, and it also doesn't it work when I explicitly direct it to the root folder by using either fs.unlink("./" + fileName) or fs.unlink("../" + fileName), or even when I hardcode the path!
Below is my code:
s3.putObject(params, function(err, data){
// ...
console.log("Data uploaded to S3 bucket");
fs.unlink("./" + fileName, function(err){
if(err) {
return console.log("Delete error: " + err);
}
else{
console.log("file deleted successfully");
}
});
console.log("Before process.exit()");
process.exit();
});
When run, this code logs:
Data uploaded to S3 bucket
Before process.exit()
So as you can see, it skips both the if and else statements on fs.unlink(), and doesn't delete the file. It's acting like that block of code doesn't exist at all and I can't figure out why.
You are using async unlink function that's why it is executing next statement. Use
unlinkSync instead.

Writing to a .txt file before node.js exits

I'd like my server to save some essential data when node exits and load them next time.
I tried what the answer of this question suggested, but the server seems to close before it is able to write to the file.
This is the exact code I am trying:
process.stdin.resume();
function exitHandler(options, err) {
if(!serverUp){return;}
serverUp = false;
fs.writeFile('server.txt', String(search_index),function (err) {
console.log("debug") // <-- This doesn't happen
process.exit();
});
}
//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
I think if you tried fs.writeFileSync it would solve this.
https://nodejs.org/api/fs.html#fs_fs_writefilesync_filename_data_options
The code would then be:
function exitHandler(options, err) {
if(!serverUp){return;}
serverUp = false;
fs.writeFileSync('server.txt', String(search_index));
console.log("debug");
process.exit(); // Don't think you'll need this line any more
}
The issue I believe is because of the async nature. By using the synchronous version of writeFile you're forcing the process to finish executing everything before exiting.

Node.js - Nginx 502

I'm getting a 502 error in my production environment, but not on my local install of my app, for a certain route. I've narrowed the problem down to the callback of the .aggregate() method that I'm querying the database with.
This is the callback:
function(err,f){
var f = f[0].forms;
if(err) console.log(err);
if (callback) {
res.setHeader('Content-Type', 'text/javascript');
res.send(callback + '(' + JSON.stringify(f) + ')');
} else {
res.end("Callback not set");
}
}
It works for my local install. I'm using this callback to send the object to another source using jsonp. Is there something I'm not doing correctly?
If you're logging an error, probably best to not continue to the next line of code.
if(err) {
console.log(err);
return done(err); //or send the error page, or do something other than continue on.
}
Can you see more contents of the error message?

Call a function in node.js

I am new to node.js .Here I write a sample function in node.js to print the contents of a json file as follows.
exports.getData =function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
console.log("Server running on the port 9090");
What I am doing here is I just want to read a json file and print the contents in console. But I do not know how to call the getData function. While running this code it only prints the sever running on the port..", not myjson` contents.
I know the above code is not correct
How can I call a function in node.js and print the json contents?
Node.js is just regular javascript. First off, it seems like you are missing a }. Since it makes the question easier to understand, I will assume that your console.log("Server... is outside exports.getData.
You would just call your function like any other:
...
console.log("Server running on the port 9090");
exports.getData();
I would note that you have a callback argument in your getData function but you are not calling it. Perhaps it is meant to be called like so:
exports.getData = function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
callback(json);
});
}
console.log("Server running on the port 9090");
exports.getData(function (json) {
console.log(json);
});
Truthfully, your getData function is a little redundant without any more content to it since it does nothing more than just wrap readJSONFile.
Don't take this the wrong way, but your code appears to be a mixed up mess of unrelated examples. I recommend you start by learning the basics of JavaScript and node.js (for example, read Eloquent JavaScript and Felix's Node.js Beginners Guide).
But on to your code. First of all, you are creating a function (called getData) and exporting it. Then you're printing "Server running on the port 9090". There is no server code in your script, and the function you created is never executed.
I think this is what you intended to write:
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
Assuming that readJSONFile is a real function.

Categories

Resources