error ENOENT,open with gridFS and node js - javascript

I am trying to save a project and its file using GridFS. I want to save project first and use "_id" of project as metadata for file.
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);
});
I am getting following error:-
ENOENT, open '/tmp/45e85388793de'
I know that this error comes when the directory does not exists. As you can see I am writing the file after saving the project since I need to link the file to the project. That's why I have written the code to save the file inside callback function of project.save() but it is not working there. If I put the same code outside the .save block the same code works perfectly for same path. (I have displayed the path both inside and outside and they are same)

Finally I was able to fix this myself:-
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).

Related

How to edit File in perfoce with node js?

If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});
Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.

upload a file in Node.JS

I'm using multiparty for uploading a file; I'm so new to Node.JS and streaming; so my question is, is it right if I stream the file by the file.path which is returned in form.parse() like the way I'm doing in my attempted code? I mean this is absolute path and obviously is working on localhost because it is the absolute path of my current server which is localhost, but is it going to work when the user attempts to upload a file from their computer too?
form.parse(req, function (err, fields, files) {
var rs= fs.createReadStream(files.file[0].path);
var fileDate;
rs.on('readable', function () {
while (null !== (chunk = rs.read())) {
fileDate += chunk;
}
});
rs.on('end', function () {
console.log('importedData', fileDate);
});
});
Thanks, please let me know if you need more clarification!
That looks correct. By default, uploaded files are put in a temporary folder, if you're using Linux this will likely be /tmp, your users' files will end up in the same place when they upload their files through your front-end.

fs.writeFile has no errors, but fails to write file

I am using node.js, trying to save a file, no errors are thrown, yes the image won't save. This is how I am saving the file:
var url = 'captures/' + getFileName() + '.png';
fs.writeFile(url, base64, 'base64', function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
With a helper to make the file names for me:
function getFileName(){
var d = new Date()
return d.getMonth()+'-'+d.getDate()+'-'+d.getYear()+'-'+d.getHours()+'-'+d.getMinutes()+d.getSeconds();
}
Anyone had trouble with this?
the problem is because this call is async and probably is loosing the context right after, I was able to fix it on my end by using fs.writeFileSync which does it synchronously. hope this helps
Add a console.log('captures/' + getFileName()) just to make sure your file name is correct. When I had this problem it turned out that I had a problem with the file path/name and node just wasn't throwing me an error to explain.
For Typescript version,
Just sharing my experience here, In my use case had a JSON file where I used to store some temporary data read it and make some changes and update it and store that updated data to same JSON file will be used for next cycle.
fs.writeFile was not throwing any error at same time it was not updating my JSON file where as JS version worked well, Then I realized that typescript made these changes in my root or src directory. Created another JSON file there.
If you want to write your file asynchronously, try using fs/promises instead of fs.
const { writeFile } = require("fs/promises");
(async () => {
await writeFile('myFile.txt', 'my content', (err) => {});
})();
writeFile from fs is void. It will execute asynchronously but not in the async-await meaning. writeFile from fs/promises returns a Promise so async-await will work as expected.
Learn more here: https://nodejs.org/api/fs.html#callback-example
There might be a permission issue.
go inside the directory that you are saving your files and then
sudo chmod 777 .

OSX Node.js File upload ENOENT

I've been working with Node.js for a project and everything has been going well until now. I'm using express as well with node. Overall my goal is extremely simple...upload an image to the server in an uploads folder. The odd thing is the upload itself actually works but when I go to use the "rename" function it says the path is wrong/permissions with this error: ENOENT.
I've also tested to make sure that the path is 100% correct when being used by calling the read function to check for the file path. Seems to only break when it tries to modify the file so I've deduced it's a permissions issue (unless there's some sort of special requirement for the rename function). I noticed that every time a file gets uploaded the permissions set to "custom" and only give read permissions to every user except my username. I'll post the code that's related to this problem below:
/app/routes.js
var fs = require('fs');
app.post('/api/file-upload/:page_id', function(req, res) {
// fs.readFile(tmp_path, function (err, data) {
// if (err) throw err;
// console.log(data);
// });
var target_path = './public/images/' + req.files.featuredimg.name;
fs.rename(req.files.featuredimg.path, target_path, function(err) {
if (err) throw err;
fs.unlink(tmp_path, function() {
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.featuredimg.size + ' bytes');
});
});
});
server.js
app.use(express.bodyParser({uploadDir:'./uploads'}));
Everything ends up in the root folder next to server.js in /uploads which works as intended. I just can't seem to modify them. I've tried everything I can think of and have looked up the problem. Hopefully it's a simple fix.
Hopefully someone out there can help me out with this problem. I'd really appreciate it!
Make sure you have created images folder under public. I had similar issue.

Upload file using NodeJS and node-formidable

I succeed uploading file using node.js and the formidable module yet,
the file that got save on the disk is in some kind of a bad format ( bad encoding)
e.g. if I upload an image I can't view it, if I upload a txt file gedit provide the following msg:
"gedit has not been able to detect the character encoding.
Please check that you are not trying to open a binary file.
Select a character encoding from the menu and try again."
here is the code:
form.encoding = 'utf-8';
form.parse(req, function(err, fields, files) {
fs.writeFile('test.js', files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
The problem is the that files.upload is not the content of the file, it is an instance of the File class from node-formidable.
Look at:
https://github.com/felixge/node-formidable/blob/master/lib/file.js
Instead of trying to write the file to disk again, you can just access the path to uploaded file like this and use fs.rename() to move it where you want:
fs.rename(files.upload.path, 'yournewfilename', function (err) { throw err; });
Is the form set to enctype="multipart/form-data"?
I've only used formidable with Express - the Express example works fine:
https://github.com/visionmedia/express/tree/master/examples/multipart

Categories