node.js path.rename() throws error despite working correctly - node.js

I am renaming files and are getting some weird behavior. It both works and throws an error.
This is the code:
var fs = require('fs');
var file = {
rename: function(from, to){
fs.rename(from, to, function (err) {
if (err) throw err;
console.log("[i] Renamed " + from + " to " + to);
});
}
}
When using it I get this console output:
main.js:1153 [i] Renamed E:\images\oldName.jpg to E:\images\newName.jpg
main.js:1152 Uncaught Error: ENOENT: no such file or directory, rename 'E:\images\oldName.jpg' -> 'E:\images\newName.jpg'
main.js:1152 (anonymous function)
fs.js:73 (anonymous function)
I don't understand what the problem is. The file is renamed anyway.
Also, it doesn't happen if the file is moved to another folder.
Why is this happening and do I have to worry about it?

The function is being called twice. That means the second time it's called the file is no longer there, leading to the 'no such file or directory'. I notice you're using windows which might also be part of the issue. Are you by any chance using fs.watch to call this function? You might be seeing an inherit problem in fs.watch under Windows duplicating events. If so, there's some example code that might help you.

Related

How to read the contents of a file onto the console using Nodejs

I am going back to learning js after many years off and all i want to do is read the contents of a file onto the console using Nodejs. I found the sample code. Nice and simple. I have spent over an hour trying to figure out why it will not find the file. This is sample right off the documentation and i made it exactly like the example to debug it. The absolute only difference is the name joe is replaced with my user folder.
const fs = require('fs')
fs.readFile('/Users/gendi/test.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
})
It runs fine except it will not find test.text. no matter what. I receive the following error and no matter how i format the file path. Nothing.
C:\Users\gendi>node readfile.js
[Error: ENOENT: no such file or directory, open 'C:\Users\gendi\test.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\gendi\\pcsSnipe\\test.txt'
}
You can also only pass in the file path as 'test.txt' and the exact same results come up. on the first part of the error msg the path looks formatted correctly but on the last line of the error msg it is not? Its been years.. so i know i am missing something really simple. I assure that file is there!! Thank you in advance and forgive my ineptness.
The fs module requires an exact path to the file you'd like to read. A simple fix to this would be to add __dirname which will return the directory path along with the path of your file.
// Define modules
const fs = require('fs');
const path = require('path');
// Read the file
fs.readFile(path.join(__dirname, '/Users/gendi/test.txt'), 'utf8' , (err, data) => {
if (err) // If FS returned an error
return console.error(err); // Log the error and return
console.log(data); // If the reading was successful, log the data
});
It works if you remove the file extention, '.txt' . Idk why it make a differnce. maybe the "." is throwing it off but it doesn't matter in this respect. Thank you

Error writing a file using 'fs' in Node

I'm trying to write to a file using the following function:
function writeFile (data, callback) {
var fs = require('fs');
var now = new Date();
fs.writeFile(now.toISOString() + ".json", data, function(err) {
if (err) {
return console.log(err);
} else {
console.log(true);
}
});
}
but im getting an error like this:
{ Error: ENOENT: no such file or directory, open 'C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28\2017_19:47:55.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Me\\WebstormProjects\\blah-blah\\client\\6\\28\\2017_19:47:55.json' }
I'm trying to create a file every time I run the program, but that doesn't seem to work very well because it says file does not exist. Is there anything im doing wrong? BTW, im running this on windows
EDIT: It was indeed wrong file name that was bugging the saving process
When you call fs.writeFile() you have to pass it a filename/path:
Where the parent directory in the path already exists.
Where the path/filename contains only characters that are legal for your OS.
It appears you are likely failing both of these unless you've pre-created the directory: C:\Users\Ruslan\WebstormProjects\communication-system\client\6\28. And, if this is running on Windows, then you also can't use : in a filename.
Assume you actually want the path to be C:\Users\Ruslan\WebstormProjects\communication-system\client and what the filename to be based on your now.toISOString(), the usual work-around is to replace path separators and other invalid filename characters with safe characters to you convert your now.toISOString() to something that is always a safe filename. In this case, you could do this:
// replace forward and back slashes and colons with an underscore
// to make sure this is a legal OS filename
let filename = now.toISOString().replace(/[\/\\:]/g, "_") + ".json";
fs.writeFile(filename, ....)

error ENOENT,open '/tmp/45e85388793de' in nodejs

I am trying to save project and its file in GridFS. I want to save project first and using "_id" of project as metadata for file I want to save file. When i tried so i am getting ENOENT, open '/tmp/45e85388793de' error. here is my code
newProject.save(function (err,project) {
if (err) {
console.log('save error', err);
}
console.log("project added");
var id=poject._id;
var filepath = req.files.file.path;
var filename = req.files.file.name;
var writestream = gfs.createWriteStream({ filename: filename, metadata:id });
console.log(filepath);
fs.createReadStream(filepath)
.on('end', function() {
})
.on('error', function(err) {
console.log("error encountered"+err);//ENOENT,open error
})
.pipe(writestream);
});
Why i am getting this error and how to resolve it?
ENOENT in this context means "No such file or directory." It means the filepath you are trying to read with createReadStream does not exist.
I think you are getting this error since :
Your file is saved in a temporary location.
When you are inside the callback function your file is removed from that location and you are getting "No such file" error. Path and other variables still exists as part of js and that's why you are able to print them in console.
Solution:
Above(Outside) callback function move your file to some other permanent location using:
fs.rename(req.files.file.path, "./someKnownPath/filename");
Keep note of that location. In your callback function use the new location as path and try saving the file in gridfs. Once the file is saved you may delete it file from that location(/someKnownPath/filename).
This error was occuring for me as well. And the reason was temp directory was not in place. After I created manually and gave a try, it worked.
Now I have shifted to creating directory on the fly through node.js itself.

Unable to read a saved file in heroku

I am using NodeJS on heroku.
I read a file from another server and save it into my application in the /temp directory.
Next, I read the same file to pass it on to my client.
The code that saves the file and then subsequently reads it is:
http.request(options, function (pdfResponse) {
var filename = Math.random().toString(36).slice(2) + '.pdf',
filepath = nodePath.join(process.cwd(),'temp/' + filename);
pdfResponse.on('end', function () {
fs.readFile(filepath, function (err, contents) {
//Stuff to do after reading
});
});
//Read the response and save it directly into a file
pdfResponse.pipe(fs.createWriteStream(filepath));
});
This works well on my localhost.
However, when deployed to heroku, I get the following error:
events.js:72
throw er; // Unhandled 'error' event
Error: ENOENT, open '/app/temp/nvks0626yjf0qkt9.pdf'
Process exited with status 8
State changed from up to crashed
I am using process.cwd() to ensure that the path is correctly used. But even then it did not help. As per the heroku documentation, I am free to create files in the applications directory, which I am doing. But I can't figure out why this is failing to read the file...
The error you describe there is consistent with /app/temp/ not existing. You need to create it before you start writing in it. The idea is:
var fs = require("fs");
var path = require("path");
var temp_dir = path.join(process.cwd(), 'temp/');
if (!fs.existsSync(temp_dir))
fs.mkdirSync(temp_dir);
I've used the sync version of the calls for illustrations purposes only. This code should be part of the start up code for your app (instead of being called for each request) and how you should structure it depends on your specific application.

In node.js why i'm not getting error while trying to write the non existing file

In the below code,i'm trying to write the non existing file 'doesnotexist.text' but still i'm getting the result as success.
var fs = require('fs');
fs.writeFile('doesnotexist.text', 'Hello World!', function (err) {
if (err) {
console.log('error is '+err);
return;
}
else{
console.log('success.');
}
});
Because the writeFile function creates the file if it does not exist.
Basically, you can change the behavior of this function by submitting an options object as third parameter, as described in the documentation. For the flags property you can provide any value from the ones described in the documentation for fs.open.
For write, they are:
w - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx - Like w but opens the file in exclusive mode.
w+ - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ - Like w+ but opens the file in exclusive mode.
The default value for writeFile is w, hence the file is created if it does not exist. As there is no option that provides an error when the file does not exist, you need an additional check whether the file already exists.
For this, check out the fs.exists function (see documentation for details).
Basically, your code should somewhat like this:
var fs = require('fs');
fs.exists('foo.txt', function (exists) {
if (!exists) {
return 'Error, file foo.txt does not exist!';
}
fs.writeFile('foo.txt', ...);
});

Resources