The exception object in NodeJS has an unusual structure. I'd like to be able to access the error message, but it's not a named attribute of the object. For example:
var fs = require("fs");
function main() {
"use strict";
try {
var stats = fs.statSync("./nonexistantFile.txt");
console.log(stats);
}
catch (exception) {
console.error("exception: " + JSON.stringify(exception));
console.log(exception);
}
};
main();
This code prints the following output:
exception: {"errno":-2,"code":"ENOENT","syscall":"stat","path":"./nonexistantFile.txt"}
{ [Error: ENOENT: no such file or directory, stat './nonexistantFile.txt']
errno: -2,
code: 'ENOENT',
syscall: 'stat',
path: './nonexistantFile.txt' }
You can see that console.log() is printing an error text message in a way that makes it appear to be part of the object. Is that text part of the exception object? Or is it something that console.log() is adding?
I would like to be able to capture the error text message and store it. How do I access that message?
Just use exception.message.
More information can be found here: Error at MDN Web Docs
Related
I have a file system function which deletes a file then creates a new one with all new data, I am looking for a possible fix for an error that occurs randomly, and not every time, but around every other time. Here is my current code:
try {
if(fs.existsSync(file)) {
fs.unlink(file, function (err) {});
}
} catch (error){
console.log('There was no file to be deleted');
}
fs.open(file, 'w', function (err, file) {
if (err) throw err;
});
var logger = fs.createWriteStream(file, {
flags: 'a' // 'a' means appending (old data will be preserved)
});
which throws the error occasionally:
C:\Users\codel\OneDrive\Documents\BattlEye\index.js:265
if (err) throw err;
^
Error: EPERM: operation not permitted, open 'C:\Users\codel\OneDrive\Documents\BattlEye\files\610636905440215071.txt'
Emitted 'error' event on WriteStream instance at:
at internal/fs/streams.js:375:14
at FSReqCallback.oncomplete (fs.js:171:23) {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\OneDrive\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
First thing that is noticeable is that this is a cloud drive(OneDrive). With my lack of knowledge about permissions, I decided to test out if the problem was in the OneDrive by transferrring the file to my harddrive. The results were not surprising. It didn't change a thing.
C:\Users\codel\Documents\BattlEye\index.js:265
if (err) throw err;
^
[Error: EPERM: operation not permitted, open 'C:\Users\codel\Documents\BattlEye\files\610636905440215071.txt'] {
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'C:\\Users\\codel\\Documents\\BattlEye\\files\\610636905440215071.txt'
}
But the Emmitted 'error' event on WriteStream disappeared from the error log.
Any ideas on why this error is happening and how to fix it?
It looks like you're using asychronous fs calls. Async calls do not work like that.
You can do a search for NodeJS asynchronous programming.
I am using this block of code to create and write a new directory and a file.
I just started to learn nodejs
var lib = {};
lib.baseDir = path.join(__dirname,'/../.data/');
lib.create = function(dir,file,data,callback){
fs.open(lib.baseDir+dir+'/'+file+'.json', 'wx', function(err, fileDescriptor){
if(!err && fileDescriptor){
var stringData = JSON.stringify(data);
// Write to file and close it
fs.writeFile(fileDescriptor, stringData,function(err){
if(!err){
fs.close(fileDescriptor,function(err){
if(!err){
callback(false);
} else {
callback('Error closing new file');
}
});
} else {
callback('Error writing to new file'+'lib.baseDir');
}
});
} else {
callback(err);
}
});
};
but I am repeatedly getting the error
{ Error: ENOENT: no such file or directory, open 'C:\Users\Jawahr\Documents\GitHub\node-api\.data\test\newFile.json'
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\Jawahr\\Documents\\GitHub\\node-
api\\.data\\test\\newFile.json' }
calling this library in a index.js as
var _data = require('./lib/data');
_data.create('test','newFile', {"asdksadlk" : "asldj"} ,function(err) {
console.log('this was the error ',err);
});
I've been stuck here for a while, is it because the pathname and filename contained the part "C:" which has colon a reserved char in windows 10, if it is the problem how to solve this.
using windows 10 and NodeJs 8.6.
Can you try this -
fs.open(lib.baseDir+dir+'/'+file+'.json', 'w', function(err, fileDescriptor){
It looks like 'wx' throws an error if file exists -
'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' - Like 'w' but fails if the path exists.
'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 fails if the path exists.
Referred from here
Looks like your put non-existing or non-accessible path to your file. Look:
fs.open('/path/is/not/exists/xx.js','wx',(err,fd)=>{
if (err) {
console.log(err.message);
}
});
and got
Error: ENOENT: no such file or directory, open '/path/is/not/exists/xx.js'
In case when file is already exists you will got something like Error: EEXIST: file already exists, open '...'
And last, but not least. Instead of lib.baseDir+dir+'/'+file+'.json' better solution is use path.join(lib.baseDir,dir,file+'.json') from path module
Add a check for directory or create before fs.open
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
Then the rest of your code will work. as fs.open only creates file if it doesn't exist, it does not create directory
Update: I was able to find the error in my code. The problem was that I didn't close my opening parenthesis with closing ones in my console.log for my notes.js.
I started a course on node.js and I am learning how to call other functions created from files on my local system. I have the directory node-notes in which I have two javascript files, app.js and notes.js. I am calling my notes.js in my app.js. I made a simple console.log() call just to make sure its working right in my notes.js. But when I try to run my code using the command node app.js I am getting the error below.
Update: I am using Node 10.0.0
I have no idea what this means so can someone please explain what the error is and how I can fix it. Below I will post both codes for my app.js and notes.js
app.js
console.log("STARTING app.js")
// calling modules using require
// calling functions in fs module and putting in the
// variable fs
const fs = require('fs');
const os = require('os');
const notes = require('./notes.js');
var user = os.userInfo();
console.log(user);
fs.appendFile('greetings.txt', 'Hello World!' + user.username , function(err){
if(err){
console.log("There was an error")
}else{
console.log("It was successful")
}
});
notes.js
console.log("Calling notes.js")
In notes.js you are missing a " to end the string.
console.log("Calling notes.js) should be console.log("Calling notes.js")
Thus you get a SyntaxError: Invalid or unexpected token
I am looking for a way to delete folders that contain files in node.js ?
I know there exists a way to delete empty folders using fs.rmdir(), and i tried using the npm rimraf module that provides the function "rm -rf" for node.js
socket.on("end", function (data) {
rimraf("./a/b/c", function(err){
if(err){
console.log(err);
}
});
});
but i keep getting this error.
{ [Error: ENOTEMPTY: directory not empty, rmdir './a/b/c']
errno: -39,
code: 'ENOTEMPTY',
syscall: 'rmdir',
path: './a/b/c' }
So I tried another way around this issue, first i empty the directory then i delete the directory
socket.on("end", function (data) {
rimraf("./a/b/c/*", function(err){
if(err){
console.log(err);
}else{
fs.rmdir("./a/b/c")
}
});
});
but then i get this error
Error: ENOTEMPTY: directory not empty, rmdir './a/b/c'
at Error (native)
I checked the folders the rimraf deletes the files but i don't see why i am still getting an error with fs.rmdir().
Edit :
I looked up a different module called fs-extra and came up with this.
fse.emptyDir("a/b/c/", function(err){
if(err){
console.log(err);
} else {
console.log("doneaaaa")
fse.remove("a/b/c",function(err){
if(err){
console.log(err);
} else {
console.log('doneaswell');
}
});
}
});
Now i get this error :
doneaaaa
{ [Error: EBUSY: resource busy or locked, unlink 'a/b/c/.nfs000000002ab5000d00000072']
errno: -16,
code: 'EBUSY',
syscall: 'unlink',
path: 'a/b/c/.nfs000000002ab5000d00000072' }
As you can see i get the past the first part of the function that deletes the files from the folder but when it comes to deleting the folder it throws the EBUSY error.
Thank you in advance !
Regardin the EBUSY error, do one thing. Do console.log(process.cwd()) to see what directory Node process is in before it tries to delete the folder. If Node is in the same folder it is trying to delete, then it will issue the EBUSY error. I had that happen to me in a Node.js application I'm developing. The solution was to change directory (process.chdir(new directory)) to something other than the one I'm trying to delete before I attempt to delete it, and problem solved. This happened on Windows by the way.
To remove it syncronously:
var fs = require('fs');
var deleteFolderRecursive = function(path) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
Im getting this error:
Error: Command failed: execvp(): Permission denied
When I do a simple node-imagemagick script:
im = require('imagemagick');
im.identify.path = '/tmp/node_thumbs/';
im.identify('cool.jpg',function(err,features){
if(err) throw err;
console.log(features);
});
Any ideas on what could be causing this?
The permission denied is from trying to launch the ImageMagick command, not in the process of executing it.
If you look at the documentation, identify.path is "Path to the identify program." In this case, you're redefining the path to the executable as /tmp/node_thumbs/, which presumably is not the executable.
You probably simply want:
var im = require("imagemagick");
im.identify('/tmp/node_thumbs/cool.jpg',function...