Error in fs.readFileSync() in nodejs - node.js

I am calling a sync call using require('fs'); in nodejs
var folder_path = '/home/abc';
var myfiles = ['a.png','b.png'];
_.each(myfiles, function(name){
var data = fs.readFileSync(folder_path+'/'+name);
if(data){
// Some operation
}
});
while calling that function i'm getting Error: EISDIR, illegal operation on a directory
fs.js:488
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EISDIR, illegal operation on a directory
at Object.fs.readSync (fs.js:488:19)
at Object.fs.readFileSync (fs.js:322:28)
at /home/coader/dev/api/controllers/MyController.js:66:30
at Function.forEach ( /home/coader/dev/node_modules/sails/node_modules/lodash/dist/lodash.js:3298:15)
at /home/coader/dev/api/controllers/MyController.js:41:11
at Object.oncomplete (fs.js:108:15)
error: Forever detected script exited with code: 8
Details
$ node -v
v0.10.37
$ nodejs -v
v0.10.37
$ npm -v
1.4.28
Any answer will be appreciable.
Thanks

I think you might have to settle for "myfiles.forEach(function(name)"
var folder_path = '/home/abc';
var myfiles = ['a.png','b.png'];
myfiles.forEach(function(name){
var data = fs.readFileSync(folder_path+'/'+name);
if(data){
// Some operation
}
});

Related

How to handle gRPC error crashing Node app

I have a simple Express App communicating with another over gRPC, it appears to be crashing on an error event.
events.js:167
throw er; // Unhandled 'error' event
^
Error: 2 UNKNOWN: Stream removed
at Object.exports.createStatusError (/home/justin/singles-api/node_modules/grpc/src/common.js:91:15)
at ClientReadableStream._emitStatusIfDone (/home/justin/singles-api/node_modules/grpc/src/client.js:233:26)
at ClientReadableStream._receiveStatus (/home/justin/singles-api/node_modules/grpc/src/client.js:211:8)
at Object.onReceiveStatus (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1272:15)
at InterceptingListener._callNext (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:618:8)
at /home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1029:24
Emitted 'error' event at:
at ClientReadableStream._emitStatusIfDone (/home/justin/singles-api/node_modules/grpc/src/client.js:234:12)
at ClientReadableStream._receiveStatus (/home/justin/singles-api/node_modules/grpc/src/client.js:211:8)
[... lines matching original stack trace ...]
at /home/justin/singles-api/node_modules/grpc/src/client_interceptors.js:1029:24
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! singles-api#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the singles-api#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I'm using some minimal example code for gRPC, how would I go about handling this to prevent the crash? as I'm not quite sure what it is i'm trying to prevent, presumably just a broken/restarting stream?
var lnrpcDescriptor = grpc.load("./rpc.proto");
var lnrpc = lnrpcDescriptor.lnrpc;
var lnd = new lnrpc.Lightning(hostport, credentials);
var call = lnd.subscribeInvoices(request)
call.on('data', function(response) {
if (response.settle_index === '0') {
console.log("New Invoice Issued: " + response.payment_request)
}
else {
//iterate through array to find who paid their invoice and update the db
for (var i = 0; i < loadedDB.db.Node.length; i++) {
if (loadedDB.db.Node[i].add_index == response.add_index) {
console.log("Node " + loadedDB.db.Node[i].Id + " has settled their invoice.");
loadedDB.db.Node[i].isSettled = true;
saveDB.writeEntry();
}
}
}
});
call.on('status', function(status) {
console.log(status);
});
call.on('end', function() {
console.log('subscribeInvoices stream ended')
});

Windows NodeJS: always get either "Error: ENOENT: no such file or directory, open" or "Error: EACCES: permission denied, open"

Here is my code:
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('C:/text.txt', { flags: 'a' });
// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;
console.log = function () {
logFile.write(util.format.apply(null, arguments) + '\n');
logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
No matter what I type instead of "C:/text.txt" I either get
Error: ENOENT: no such file or directory, open
or
Error: EACCES: permission denied, open
I tried everything such as "run as administrator" and "elevate", but when it's not the second error message, it's the first one; and when it's not the first one, it's the second one.
I'm soooo confused
For windows it's better to use \\ in the path to avoid some problems.
C:\\text.txt
This path I use to include pdftk.exe:
C:\\PDFtk\\bin\\pdftk.exe

Unhandled 'error' event when extracting zip file with nodejs

I want to download a zip file and extract it with nodejs. This is what I have done so far:
var fs = require('fs');
var wget = require('wget-improved');
var filesizeHumanReadable = require('filesize');
var unzip = require('unzip');
var downloadCSS = function() {
var src = 'http://7-zip.org/a/7za920.zip';
var output = '/tmp/7z.zip';
var options = {};
var download = wget.download(src, output, options);
download.on('error', function(err) {
console.log(err);
});
download.on('start', function(fileSize) {
console.log(filesizeHumanReadable(fileSize));
});
download.on('end', function(outputMessage) {
console.log(outputMessage);
console.log(output);
fs.createReadStream(output).pipe(unzip.Extract({ path: '/tmp/' }));
});
download.on('progress', function(progress) {
// code to show progress bar
});
}
The error message I get when running it:
mles-MacBook-Pro:test-api mles$ node index.js
375.83 KB
Finished writing to disk
/tmp/7z.zip
events.js:85
throw er; // Unhandled 'error' event
^
Error: EPERM, unlink '/tmp'
at Error (native)
Now I'm a bit baffled how to handle the error event and what my actual error is?
Does the process have enough permission to write to /tmp? Does /tmp already have some files?
Because unlink is a node.js function to delete directories. Apparently, unzip.Extract calls it. So, unlink fails if the folder isn't empty (in your case /tmp).
Setting the unzip location to a specific directory fixes it
fs.createReadStream(output).pipe(unzip.Extract({ path: '/tmp/7zip' }));
I'm marking mostruash answer as correct since he brought me on the right track.

Why does the errno in node-webkit differ from Node.js?

Run the same code in node-webkit and Node.js
var fs = require('fs')
// var fs = process.mainModule.exports.fs // node-webkit
fs.readFile('/xxxx/xx','utf-8', function (e) {
console.log(e)
})
In Node.js, the errno is 34
{ [Error: ENOENT, open '/xxxxx/xx'] errno: 34, code: 'ENOENT', path: '/xxxxx/xx' }
In node-webkit, it's -2
{"errno":-2,"code":"ENOENT","path":"/xxxx/xx"}
Why the errnos are different?
Is there a errno cheat sheet for node-webkit like this one for Node.js?
I'm having the same error and its due to using a relative path. Try to reading fro xx directly, not from /xxxx/xx
Hope it solves it

Node JS - child_process spawn('npm install') in Grunt task results in ENOENT error

I'm having some difficulty with a Grunt task I'm authoring. I'm trying to execute npm install, followed by bower install, followed by a grunt hub target (to trigger a build command for multiple sub-projects).
The problem I'm encountering lies with child_process. I get spawn ENOENT error if I run the following commands in my grunt task, with the npm install spawn command that's currently commented out:
var path = require('path'),
projectPath = path.resolve(process.cwd(), this.data.activity );
grunt.log.debug('project path computed as: ', projectPath);
process.chdir( projectPath );
console.log('current dir is: ', process.cwd());
console.log('EVN is: ', process.env);
var spawnProcess = spawn('ls');
// var spawnProcess = spawn('npm install');
spawnProcess.stdout.on('data', function (data) {
console.log('' + data);
});
spawnProcess.stderr.on('data', function(data) {
console.log('something went wrong installing deps for ' + path + '. Error: ', data);
});
spawnProcess.on('close', function (exitCode) {
console.log( 'ls has finished with Exit Code: ' + exitCode);
});
the current code (with ls instead of npm install) results in:
running "install:projects" (install) task[D] Task source: /Users/zedd45/proj/Gruntfile.js
Verifying property install.projects exists in config...OK
File: [no files]
[D] project path computed as: /Users/zedd45/proj/activity/web/client
current dir is: /Users/zedd45/proj/activity/web/client
EVN (abbreviated) is: {
TERM_PROGRAM: 'iTerm.app',
SHELL: '/bin/bash',
PWD: '/Users/zedd45/proj',
...
OLDPWD: '/Users/zedd45/proj/activity/web/client',
_: '/usr/local/bin/grunt' }
GruntFile.js
bower.json
package.json
this_is_the_directory_you_are_looking_for.txt
ls has finished with Exit Code: 0
but if I change 'ls' to 'npm install' I get instead
``Fatal error: spawn ENOENT
immediately following the ENV print.
I have tried chmod 777 for that directory, which doesn't seem to help.
I have also tried:
// var spawnProcess = spawn('npm install', {'cwd': projectPath});
and
// var spawnProcess = spawn('npm install', [], {'cwd': projectPath});
The former results in
Warning: Object # has no method 'slice' Use --force to
continue.
the later still results in the ENOENT error.
Any help with exactly what this ENOENT error is would probably help a great deal; I haven't had much success with Googling it nor with the child process API docs
Double check the docs on child_process.spawn again. The first argument should be only the command to run and the second is the arguments:
var npm = spawn('npm', ['install'], { cwd: projectPath });

Resources