SMB-Get Nodejs getaddrinfo ENOTFOUND - javascript

I'm currently trying to connect to a SMB server from a Debian machine. i've downloaded ths SMB2-Client from https://github.com/bchelli/node-smb2 , ive done the example
var SMB2 = require('smb2');
// create an SMB2 instance
var smb2Client = new SMB2({
share:'\\\\xxx/appfolder/\\'
, domain:'xxx'
, username:'teste'
, password:'teste'
});
smb2Client.exists('/Base_dados.mdb', function (err, exists) {
if (err) throw err;
console.log(exists ? "it's there" : "it's not there!");
});
i'm getting the current error
/home/sergio/Desktop/node-access/index.js:14
if (err) throw err;
^
If anyone has any idea on how to solve this, would be greatly appreciated.
Regards.

the problem was based on the path
'\\\\xxx\\app_folder'
fixed the problem.

Related

NodeJS/JavaScript - Read File by passing command results from child_process as filepath for "fs.readFile"

I am currently having trouble with what is most likely a very simple function for most.
I have what I call a Find & Read function.
The "find" part of the function utilises a child_process with the find -name command in order to locate a given file by name and extension,
the "Read" part of the function is where the problem seems to be.
The "Read" part of the function is supposed to use the results from the command executed in the child_process, in a seperate variable, in order to start reading the file using fs.readFile, however everything I have tried presents me with the following error in the console...
Locating File...
File Found: this/way/to/the/File.txt
Reading File...
Reading File Failed!
Error: ENOENT: no such file or directory, open 'this/way/to/the/File.txt'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at /home/user/test/index.js:23:8
at ChildProcess.exithandler (node:child_process:390:7)
at ChildProcess.emit (node:events:527:28)
at maybeClose (node:internal/child_process:1092:16)
at Socket.<anonymous> (node:internal/child_process:451:11)
at Socket.emit (node:events:527:28)
at Pipe.<anonymous> (node:net:710:12) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: 'this/way/to/the/File.txt'
}
However the isn't correct, the file actually does exist inside the directory found by the command executed in the child_process but it's still throwing me errors saying the file doesn't exist... if the file didn't exist, it wouldn't have located and printed its location in the console... so I'm not sure where the error is coming from here, hence why I've come StackOverflow for help.
I am using the JavaScript coding below to to try and achieve this...
Find & Read function
var exec = require("child_process").exec, child;
var fs = require('fs');
var path = require('path');
// This seems to be working fine to locate the file
var folder = '/just/some/folder/location/';
var file = "File.txt";
console.log("Locating File...")
console.log();
exec('find -name ' + file, { cwd: folder }, (error, stdout, stderr) => {
var filePath = stdout.substring(stdout.indexOf("./") + 2).split("\n")[0];
if (error !== null) {
console.log("Locating Failed Failed!");
console.log(error);
console.log(stderr);
return;
}
// but it fails to read the file afterwards
console.log("File Found: " + filePath); // print filepath in the log to confirm the file was found
console.log();
console.log("Reading File...");
fs.readFile(filePath, 'utf8', (error, data) => {
if (error) {
console.log('Reading File Failed');
console.log(error);
return;
}
});
});
Problem solved.
The problem was located within the filePath variable.
What was happening was, I didn't join both the folder variable & the filePath variable together with path.join() once the file was located!
For some reason as well, the instance of .trim("\n")[0]) at the end of the filePath variable needed to be changed to an instance of .trim("\n"))... Because for some reason the former coding was causing problems with the function as well.
Fix that was implemented
The below instance of the filePath variable...
var filePath = stdout.substring(stdout.indexOf("./") + 2).split("\n")[0];
Was was changed to the following...
var filePath = path.join(apkFolder, stdout.substring(stdout.indexOf("./") + 2).split("\n"));
Which now runs beautifully, the file gets located and it gets read beautifully!
Here's the Full fixed code below...
var folder = '/just/some/folder/location/';
var file = "File.txt";
console.log("Locating File...")
console.log();
exec('find -name ' + file, { cwd: folder }, (error, stdout, stderr) => {
var filePath = path.join(folder, stdout.substring(stdout.indexOf("./") + 2).split("\n")); // Fix contained here
if (error !== null) {
console.log("Locating File Failed!");
console.log(error);
console.log(stderr);
return;
}
console.log("File Found: " + filePath);
console.log();
console.log("Reading File...");
fs.readFileSync(filePath, 'utf8', (error, data) => {
if (error) {
console.log('Reading File Failed');
console.log(error);
return;
}
});
});

Node Js: How to catch a "No such file or directory" error in readline module

I'm working on a program that reads a file line by line with the readline module. First I get the file name by command line, but I want to check if the file actually exists. I have read about fs.stat() but I want to know if there is a way to catch the error directly with readline. So far I've tried this
try{
var line_reader = read_line.createInterface({
input: file_stream.createReadStream(file_name)
});
}catch(err){
console.log('Please insert a valid file name');
}
But I still get the message
Error: ENOENT: no such file or directory
The exception is thrown by createReadStream.
You need to add 'on error' case to createReadStream:
var fs = file_stream.createReadStream(file_name)
fs.on('error', function (err) {
// handle error here
});
var line_reader = read_line.createInterface({
input: fs
});
Miss read your question at the beginning and updated my answer.
A solution you could use fs.stat
Edit
// fs.stat is async
fs.stat(file_name, function(err,stat){
if (stat && stat.isFile() ) {
var line_reader = read_line.createInterface({
input: file_stream.createReadStream(file_name)
});
}
});

gulp-git: Using push results in a stream error

I'm trying to push to my remote repository using the gulp-git module from npm. The add & commit portion runs fine, but it runs into a stream error when trying to perform the remote push.
bump: function () {
var branch = argv.branch || 'development';
fs.readFile('./package.json', function (err, data) {
if (err) { return ; }
return gulp.src(['./package.json', './bower.json'])
.pipe(git.add())
.pipe(git.commit('chore(core): bump to ' + JSON.parse(data).version))
.pipe(git.push('origin', branch, function(err) {
if(err) throw (err);
}));
});
}
The stack trace:
C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:623
var written = dest.write(chunk);
^
TypeError: undefined is not a function
at write (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:623:24)
at flow (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:632:7)
at DestroyableTransform.pipeOnReadable (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:664:5)
at DestroyableTransform.emit (events.js:104:17)
at emitReadable_ (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:448:10)
at emitReadable (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:444:5)
at readableAddChunk (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:187:9)
at DestroyableTransform.Readable.push (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_readable.js:149:10)
at DestroyableTransform.Transform.push (C:\src\git\ig\node_modules\gulp-git\node_modules\through2\node_modules\readable-stream\lib_stream_transform.js:145:32)
at Array.forEach (native)
I'm running gulp-git version 1.6.0. It looks like they are at 1.7.0. Maybe the upgrade path would help however this seems like a pretty standard usage of the command, so I think it's something I'm doing wrong.
With help from stevelacy (the project admin) I was able to make it work with this code change:
.pipe(git.commit('chore(core): bump to ' + JSON.parse(data).version))
.on('end', function() {
git.push('origin', branch, function(err) {
if(err) throw (err);
});
});
It turns out that the git push command cannot be done from a stream as of yet.

replicate pouchDB document with couchDB

I have used pouchDB in one application and now I want to introduce couchDB to sync the document to remote server. Hence i followed this link http://pouchdb.com/getting-started.html i used the below code to replicate the data to couchDB
var db2 = new PouchDB('todos');
var remoteCouch = 'http://localhost:5984/_utils/database.html?couchdb_sample';
db2.changes({
since: 'now',
live: true
}).on('change', showTodos);
sync();
function sync() {
//alert("sync");
//syncDom.setAttribute('data-sync-state', 'syncing');
//var opts = {live: true};
db2.replicate.to(remoteCouch).on('complete', function () {
console.log("done");
}).on('error', function (err) {
console.log(err);
});
function addTodo(text) {
var todo = {
_id: $("#eid").val()+$("#version").val(),
title: text,
name: $("#nameid").val(),
version: $("#version").val(),
completed: false
};
db2.put(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
else{
console.log(err);
}
});}
here the title has an xml string as value. But i am facing below error
SyntaxError: Unexpected token <
at Object.parse (native)
for this line db2.replicate.to(remoteCouch). I manually created a new document in couchDb database and entered the same data it gave no error but when i try replicating it shows syntax error. Can anyone please hint me where I have gone wrong
http://localhost:5984/_utils/database.html?couchdb_sample
Points to a HTML site (copied over from the browsers address bar, right?). Remove the middle part:
http://localhost:5984/couchdb_sample
It look like you have not defined the remote database in the way PouchDb is expecting. You should use the "new PouchDb" call. The second line of your code is:
var remoteCouch = 'http://localhost:5984/_utils/database.html?couchdb_sample';
but I think it should be like this:
var remoteCouch = new PouchDB('http://localhost:5984/couchdb_sample');
I am not clear from your code what the name of the remote database is, but it would not normally end in ".html" as Ingo Radatz pointed out, so I have assumed it is couchdb_sample above. There is more information about replication on the PouchDb site.

Reference error is not thrown from MongoDB callback

Introduction
All people know that if we call undefined.test we will receive the following error (same for both: NodeJS and Javascript):
$ node
> undefined.test
TypeError: Cannot read property 'test' of undefined
at repl:1:11
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)
That's correct!
How did I find the problem?
Passed week I wasted about 30 minutes in debugging the following problem: A script was stopping accidentally and no error was thrown.
I had the urls variable that was supposed to be an object:
var urls = settings.urls || {};
Then in next lines I needed to get shop key of urls that was a string:
var shop = urls.shop || "/";
I started adding console.log to find the values of variables:
console.log(urls); // undefined
var shop = urls.shop || "/";
console.log("Passed"); // This isn't run.
The problem in my script was that I was redefining a new urls variable that was making the urls undefined, but the question is: why cannot read property "shop" of undefined didn't appear here? Because urls was really undefined.
We know that the following is happening in both: NodeJS and Javascript:
var a = 10;
foo(function () {
console.log(a); // undefined
var a = 10;
});
function foo(callback) { callback(); }
The question
After debugging the problem I found that this problem comes from Mongo: inside of Mongo callbacks if we call undefined.something we DON'T get the error.
I've created a small script that demonstrates this:
var mongo = require("mongodb");
// Mongo server
var server = mongo.Server("127.0.0.1", 27017);
var db = new mongo.Db("test", server, { safe: true });
console.log("> START");
// Open database
console.log("Opening database.");
db.open(function(err, db) {
if (err) { return console.log("Cannot open database."); }
// get collection
console.log("No error. Opening collection.");
db.collection("col_one", function(err, collection) {
if(err) { return console.log(err) }
// do something with the collection
console.log("No error. Finding all items from collection.");
collection.find().toArray(function(err, items) {
if(err) { return console.log(err) }
console.log("No error. Items: ", items);
console.log("The following line is: undefined.shop." +
"It will stop the process.");
console.log(undefined.test); // THE ERROR DOES NOT APPEAR!
console.log("> STOP"); // this message doesn't appear.
});
});
});
My questions are:
Why the error doesn't appear? Which is the reason? (It would be great to debug together the MongoDB source code to find it.)
Why the process is stopped when calling undefined.something?
How can be this solved?
I've created a Github repository where you can download my small application that demonstrates the issue.
Interesting:
If we add a try {} catch (e) {} statement we find the error and the process continue showing the STOP message.
try {
console.log(undefined.test);
} catch (e) {
console.log(e);
}
LOGS:
> START
Opening database.
No error. Opening collection.
No error. Finding all items from collection.
No error. Items: []
The following line is: undefined.shop. It will stop the process.
[TypeError: Cannot read property 'test' of undefined]
> STOP
Looking on github.com at node-mongodb-native driver issues, you will notice that issue is solved in 1.3.18 version. But, I tested it and it does not work as expected.

Categories