Permissions To Read Windows File Across Network in NodeJS - windows

I'm trying to read a text file using NodeJS on a Mac. The file is on a Windows computer which is on the same network.
var fs = require('fs');
var file = "smb://someserver/stuff/names.txt";
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
When I run this code, I get:
> Error: ENOENT, open 'smb://someserver/stuff/names.txt'
I probably need to authenticate access to the file, but I haven't found any docs or modules that deal with this scenario. Is it possible to read/write files like this?
Update (10/22)
I've tried using UNC paths (ie \\someserver\stuff\names.txt) but I believe that is only part of the solution. Somehow I need to supply username/password/domain because this file requires special permission. Is it possible to supply permissions somehow? For example:
var fs = require('fs');
var file = '\\someserver\stuff\names.txt';
var credentials = { username:'mydomain/jsmith', password:'password' }; ???
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

You should use UNC paths if you are trying to access resources from other network drives.
var fs = require('fs');
var file = "\\someserver\stuff\names.txt";
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});

You can use the 'node-cmd' to update the credentials first and then try to read/write to the folder using the unc path.
var cmd = require("node-cmd");
const data = cmd.runSync(
"net use \\IP /user:username password"
);
// Now you do read / write using the fs
fs.readdir("\\IP")

Related

Cypress install and running

I am getting the following error/exception trying to run cypress:
Error: EEXIST: file already exists, mkdir
The tool runs and then throws up the error
The EEXIST error is another filesystem error that is encountered whenever a file or directory exists, but the attempted operation requires it not to exist. For example, you will see this error when you attempt to create a directory that already exists as shown below:
const fs = require('fs');
fs.mkdirSync('temp', (err) => {
if (err) throw err;
});
The solution here is to check if the path exists through fs.existsSync() before attempting to create it:
const fs = require('fs');
if (!fs.existsSync('temp')) {
fs.mkdirSync('temp', (err) => {
if (err) throw err;
});
}
Source: link

Electron fs - EPERM: operation not permitted, open 'C:\Windows\System32\drivers\etc\hosts'

Is there a way in electron or nodejs to ask the user to give permission to edit the file, e.g. like the popup if you want to install a program and you need the admin permissions to do so.
I don't have any problems reading the file with default permission settings. If I change the file permissions in the Windows explorer my electron app can write/edit the file, but that not solves my problem.
const fs = require("fs");
let letPathtoFile = "C:/Windows/System32/drivers/etc/hosts";
function funcReadFile() {
fs.readFile(letPathtoFile, function (err, data) {
if (err) {
return console.error(err);
}
$('#idReadFileContent').text(data);
});
}
function funcWriteFile() {
let letNewContent = $('#idWriteFileContent').val();
fs.writeFile(letPathtoFile, letNewContent, (err) => {
if (err) {
alert(err.message);
console.log(err);
return;
}
alert("File saved");
});
}
Yes, there is a way - you can use either sudo-prompt (NPM, GitHub) or electron-sudo (NPM, GitHub).
You'll need to do an exec command & a graphical OS prompt should show up.

Invalid signature string to sign Node/Cloudinary

I’m having a problem with image uploads with the Cloudinary API.
I have the app running on Heroku. I’m using Node for my backend. The app runs fine, until a user tries to post an image. I then get the following error message:
Invalid Signature ******************************. String to
sign - 'timestamp=.
I used the same setup in another app, and it works fine. I’ve followed some stack overflow threads on the problem, but I’m not getting a useful answer that I understand.
I’ve set up the environment variables in Heroku the same way I did on another app, and it works. I’ve also installed the Cloudinary and Multer packages in my package.json file.
Any ideas what I’m doing wrong here?
Below is my code:
var multer = require('multer');
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var imageFilter = function (req, file, cb) {
// accept image files only
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
return cb(new Error('Only image files are allowed!'), false);
}
cb(null, true);
};
var upload = multer({ storage: storage, fileFilter: imageFilter});
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'digi9mjbp',
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})
router.post("/", middleware.isLoggedIn, upload.single('image'),
function(req, res) {
cloudinary.v2.uploader.upload(req.file.path, function(err,result){
if(err){
req.flash("error", err.message);
return res.redirect("back");
}
// add cloudinary url for the image to the topic object under image
property
req.body.topic.image = result.secure_url;
//add image's public_id to topic object
req.body.topic.imageId = result.public_id;
// add author to topic
req.body.topic.author = {
id: req.user._id,
username: req.user.username
};
Topic.create(req.body.topic, function(err, topic){
if (err) {
req.flash('error', err.message);
return res.redirect('back');
}
res.redirect('/topics/' + topic.id);
});
});
});

Creating a Nodejs local reverse shell over Ajax?

I'm attempting to make a small node executable which has the ability to open a local shell and send and receive commands to a HTTP server.
Seems simple enough logically but what would be the best practice in implementing this?
Open a command line using Node API
Listen for commands from server URL /xmlrpc-urlhere/
When a command is received via Ajax or WebRTC? Execute it in command line
POST the command line response back to the user
This shell will be for administrative purposes.
I can't think of a good way of doing this, I've checked npm and it would seem there are some basic command line modules for node js but nothing that has this functionality.
The npm modules commander and request ought to do the trick. To get you started, here's a simple command line tool that issues a search to google and dumps the raw HTML into the console.
Eg:
./search.js puppies
#!/usr/bin/env node
var program = require('commander');
var request = require('request');
var search;
program
.version('0.0.1')
.arguments('<query>')
.action(function(query) {
search = query;
});
program.parse(process.argv);
if (typeof search === 'undefined') {
console.error('no query given!');
process.exit(1);
}
var url = 'http://google.com/search?q=' + encodeURIComponent(search);
request(url, function(err, res, body) {
if (err) {
console.error(err);
process.exit(1);
}
console.log('Search result:');
console.log(body);
process.exit(0);
});

Fastest way to check for existence of a file in NodeJs

I'm building a super simple server in node and in my onRequest listener I'm trying to determine if I should serve a static file (off the disk) or some json (probably pulled from mongo) based on the path in request.url.
Currently I'm trying to stat the file first (because I use mtime elsewhere) and if that doesn't fail then I read the contents from disk. Something like this:
fs.stat(request.url.pathname, function(err, stat) {
if (!err) {
fs.readFile(request.url.pathname, function( err, contents) {
//serve file
});
}else {
//either pull data from mongo or serve 404 error
}
});
Other than cacheing the result of fs.stat for the request.url.pathname, is there something that could speed this check up? For example, would it be just as fast to see if fs.readFile errors out instead of the stat? Or using fs.createReadStream instead of fs.readFile? Or could I potentially check for the file using something in child_process.spawn? Basically I just want to make sure I'm not spending any extra time messing w/ fileio when the request should be sent to mongo for data...
Thanks!
var fs = require('fs');
fs.exists(file, function(exists) {
if (exists) {
// serve file
} else {
// mongodb
}
});
I don't think you should be worrying about that, but rather how can you improve the caching mechanism. fs.stat is really ok for file checking, doing that in another child process would probably slow you down rather then help you here.
Connect implemented the staticCache() middleware a few months ago, as described in this blog post: http://tjholowaychuk.com/post/9682643240/connect-1-7-0-fast-static-file-memory-cache-and-more
A Least-Recently-Used (LRU) cache algo is implemented through the
Cache object, simply rotating cache objects as they are hit. This
means that increasingly popular objects maintain their positions while
others get shoved out of the stack and garbage collected.
Other resources:
http://senchalabs.github.com/connect/middleware-staticCache.html
The source code for staticCache
this snippet can help you
fs = require('fs') ;
var path = 'sth' ;
fs.stat(path, function(err, stat) {
if (err) {
if ('ENOENT' == err.code) {
//file did'nt exist so for example send 404 to client
} else {
//it is a server error so for example send 500 to client
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );
In case you want to serve a file using express, I would recommend to just use the sendFile error Handler of express
const app = require("express")();
const options = {};
options.root = process.cwd();
var sendFiles = function(res, files) {
res.sendFile(files.shift(), options, function(err) {
if (err) {
console.log(err);
console.log(files);
if(files.length === 0) {
res.status(err.status).end();
} else {
sendFiles(res, files)
}
} else {
console.log("Image Sent");
}
});
};
app.get("/getPictures", function(req, res, next) {
const files = [
"file-does-not-exist.jpg",
"file-does-not-exist-also.jpg",
"file-exists.jpg",
"file-does-not-exist.jpg"
];
sendFiles(res, files);
});
app.listen(8080);
If the file is not existent then it will go to the error that sends it self.
I made a github repo here https://github.com/dmastag/ex_fs/blob/master/index.js

Resources