How to read the contents of a file onto the console using Nodejs - node.js

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

Related

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)."

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, ....)

Node.js fs.stat not working as expected when used on module

i'm having a weird issue with fs.stat to check if a file is valid or not,
when i pass an absolute path with a variable (filePath in this case)
it appends the path of the project to the path i sent!
FileCompresser.CompressFile = (filePath,callback) =>{
console.log(filePath);
fs.stat(filePath,(err,stat)=>{
if(err){
callback(err,null);
return;
}
var readStream = fs.createReadStream(filePath).pipe(zlib.createGzip());
callback(null,readStream);
});
}
AssertionError: expected Error {
code: 'ENOENT',
errno: -4058,
path: 'C:\\carpetica\\NodeCompress\\‪‪C:\\carpetica\\delete.reg',
syscall: 'stat',
message: 'ENOENT: no such file or directory, stat \'C:\\carpetica\\NodeCompress\\‪‪C:\\carpetica\\delete.reg\''
} to not exist
yet if i do the following it works correctly :
fs.stat("C:/carpetica/delete.reg",(err,stat)=>{
if(err){
callback(err,null);
return;
}
var readStream = fs.createReadStream(filePath).pipe(zlib.createGzip());
callback(null,readStream);
});
but of course that is not good for testing... i send exactly the same value i hard coded there... yet i get that weird behavior.. this behavior doesn't happen when i run directly from the REPL without modules.
UPDATE:
found the culprit ( i think!), i tested with 2 paths, and the only thing different were the
' and the "" surrounding the strings
it("should return a compressed file",(done)=>{
var path2 = '‪F:/ISOS/linuxmint-17.1-mate-64bit.iso';//this doesnt work!
var path1 = "C:/carpetica/delete.reg";//but this does!
FileCompresser.CompressFile(path2, (err,CompressedfileStream) =>{
should.not.exists(err);
should(CompressedfileStream).be.ok();
done();
});
} );
as soon as i wrapped path2 on double quotes it worked as intended :)

writeFile no such file or directory

I have a file(data.file an image), I would like to save this image. Now an image with the same name could exist before it. I would like to overwrite if so or create it if it does not exist since before. I read that the flag "w" should do this.
Code:
fs.writeFile('/avatar/myFile.png', data.file, {
flag: "w"
}, function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
Error:
[Error: ENOENT: no such file or directory, open '/avatar/myFile.png']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/avatar/myFile.png'
This is probably because you are trying to write to root of file system instead of your app directory '/avatar/myFile.png' -> __dirname + '/avatar/myFile.png' should do the trick, also check if folder exists. node.js won't create parent folder for you.
Many of us are getting this error because parent path does not exist. E.g. you have /tmp directory available but there is no folder "foo" and you are writing to /tmp/foo/bar.txt.
To solve this, you can use mkdirp - adapted from How to write file if parent folder doesn't exist?
Option A) Using Callbacks
const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirName = require('path').dirname;
function writeFile(path, contents, cb) {
mkdirp(getDirName(path), function (err) {
if (err) return cb(err);
fs.writeFile(path, contents, cb);
});
}
Option B) Using Async/Await
Or if you have an environment where you can use async/await:
const mkdirp = require('mkdirp');
const fs = require('fs');
const writeFile = async (path, content) => {
await mkdirp(path);
fs.writeFileSync(path, content);
}
I solved a similar problem where I was trying to create a file with a name that contained characters that are not allowed. Watch out for that as well because it gives the same error message.
I ran into this error when creating some nested folders asynchronously right before creating the files. The destination folders wouldn't always be created before promises to write the files started. I solved this by using mkdirSync instead of 'mkdir' in order to create the folders synchronously.
try {
fs.mkdirSync(DestinationFolder, { recursive: true } );
} catch (e) {
console.log('Cannot create folder ', e);
}
fs.writeFile(path.join(DestinationFolder, fileName), 'File Content Here', (err) => {
if (err) throw err;
});
Actually, the error message for the file names that are not allowed in Linux/ Unix system comes up with the same error which is extremely confusing. Please check the file name if it has any of the reserved characters. These are the reserved /, >, <, |, :, & characters for Linux / Unix system. For a good read follow this link.
It tells you that the avatar folder does not exist.
Before writing a file into this folder, you need to check that a directory called "avatar" exists and if it doesn't, create it:
if (!fs.existsSync('/avatar')) {
fs.mkdirSync('/avatar', { recursive: true});
}
you can use './' as a prefix for your path.
in your example, you will write:
fs.writeFile('./avatar/myFile.png', data.file, (err) => {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
I had this error because I tried to run:
fs.writeFile(file)
fs.unlink(file)
...lots of code... probably not async issue...
fs.writeFile(file)
in the same script. The exception occurred on the second writeFile call. Removing the first two calls solved the problem.
In my case, I use async fs.mkdir() and then, without waiting for this task to complete, I tried to create a file fs.writeFile()...
As SergeS mentioned, using / attempts to write in your system root folder, but instead of using __dirname, which points to the path of the file where writeFile is invoked, you can use process.cwd() to point to the project's directory. Example:
writeFile(`${process.cwd()}/pictures/myFile.png`, data, (err) => {...});
If you want to avoid string concatenations/interpolations, you may also use path.join(process.cwd(), 'pictures', 'myFile.png') (more details, including directory creation, in this digitalocean article).

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.

Resources