I am trying to write to a mapped network drive in Node using the windows-network-drive module and the fs module.
networkDrive.mount('\\\\server', 'Z', 'username', 'password')
.then(driveLetter => {
let filePath;
filePath = path.join(driveLetter + ":\\path\\to\\directory", "message.txt");
fs.writeFile(filePath, "text", (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
})
.catch(err => {
console.log(err)
});
How can I get the connection and path to write to a remote location?
Do I need to pass in the drive letter? If so, how do I locate it?
(node:4796) UnhandledPromiseRejectionWarning:
ChildProcessError: Command failed: net use Z: "\server" /P:Yes /user:username password
System error 67 has occurred.
The network name cannot be found.
net use Z: "\server" /P:Yes /user:username password (exited with error code 2)
at callback (C:\app\location\node_modules\child-process-promise\lib\index.js:33:27)
at ChildProcess.exithandler (child_process.js:279:5)
at ChildProcess.emit (events.js:159:13)
at maybeClose (internal/child_process.js:943:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)
name: 'ChildProcessError',
code: 2,
childProcess:
{ ChildProcess: { [Function: ChildProcess] super_: [Function] },
fork: [Function],
_forkChild: [Function],
exec: [Function],
execFile: [Function],
spawn: [Function],
spawnSync: [Function: spawnSync],
execFileSync: [Function: execFileSync],
execSync: [Function: execSync] },
stdout: '',
stderr: 'System error 67 has occurred.\r\n\r\nThe network name cannot be found.\r\n\r\n' }
P.S. this code logs Z
networkDrive.mount('\\\\server\\path\\to\\directory', 'Z', 'mdadmin', 'Password1!')
.then(function (driveLetter) {
console.log(driveLetter);
fs.writeFile('L_test.txt', 'list', (err) => {
if (err) throw err
})
});
To write from a REST Service hosted in IIS, you will need to properly set the permissions on the server.
You will need to set the identity of the Application Pool of your site.
You will need to grant write permissions to match that account or account group to the folder that you are trying to write to.
Note: If you map a folder to a network drive letter through the OS, it is only defined at the user account level.
So, if you have mapped the folder location to a drive letter (in this case 'X:'), instead of writing to
fs.writeFile('X:/test.txt', 'text', (err) => {
if (err) throw err
})
You must write to to full path
fs.writeFile('\\\\servername\\path\\to\\director\\test.txt', 'text', (err) => {
if (err) throw err
})
Note: Backslashes need to be escaped, so the Windows file system will show something like \\servername\path\to\directory.
P.S. This answer includes recommendations from users l-bahr and Ctznkane525.
I am not sure what error you got, so here are a couple tips for when you are using windows-network-drive.
Escape Special Characters
Windows uses \ to separate directories. \ is a special character in a JavaScript string and must be escaped like this \\. e.g. C:\file.txt would be C:\\file.txt in a string.
Use POSIX Separation Character When You Can
Because of the added difficulty in reading a path with the escaped \, I would recommend using / instead. windows-network-drive should handle both just fine. e.g. C:\file.txt would be C:/file.txt in a string.
Example
I tried to make this match your example, but made a few changes so that it will work on any windows machine.
let networkDrive = require("windows-network-drive");
/**
* https://github.com/larrybahr/windows-network-drive
* Mount the local C: as Z:
*/
networkDrive.mount("\\\\localhost\\c$", "Z", undefined, undefined)
.then(function (driveLetter)
{
const fs = require("fs");
const path = require("path");
let filePath;
/**
* This will create a file at "Z:\message.txt" with the contents of "text"
* NOTE: Make sure to escape '\' (e.g. "\\" will translate to "\")
*/
filePath = path.join(driveLetter + ":\\", "message.txt");
fs.writeFile(filePath, "text", (err) =>
{
if (err) throw err;
console.log('The file has been saved!');
});
});
Related
Does this Nodejs code look right? Is there anything missing?
const mysql = require('mysql');
const fs = require('fs');
var config =
{
host: 'mydemoserver.mysql.database.azure.com',
user: 'myadmin#mydemoserver',
password: 'your_password',
database: 'quickstartdb',
port: 3306,
ssl: {ca: fs.readFileSync("your_path_to_ca_cert_file_BaltimoreCyberTrustRoot.crt.pem")}
};
const conn = new mysql.createConnection(config);
conn.connect(
function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:");
throw err;
}
else {
console.log("Connection established.");
readData();
}
});
function readData(){
conn.query('SELECT * FROM inventory',
function (err, results, fields) {
if (err) throw err;
else console.log('Selected ' + results.length + ' row(s).');
for (i = 0; i < results.length; i++) {
console.log('Row: ' + JSON.stringify(results[i]));
}
console.log('Done.');
})
conn.end(
function (err) {
if (err) throw err;
else console.log('Closing connection.')
});
};
This is to go inside an Azure Function that reads data from a Azure for MySQL database.
When I run it inside the Kudu window by just typing node index.js it works
When I try and test it on there Azure Function Test Page it throws a Internal Server Error 500 with the following error message
Unable to determine function entry point. If multiple functions are exported, you must indicate the entry point, either by naming it 'run' or 'index', or by naming it explicitly via the 'entryPoint' metadata property.' Stack: Error: Worker was unable to load function ListBrands: 'Unable to determine function entry point. If multiple functions are exported, you must indicate the entry point, either by naming it 'run' or 'index', or by naming it explicitly via the 'entryPoint' metadata property.' at C:\Program Files (x86)\SiteExtensions\Functions\4.14.0\workers\node\dist\src\worker-bundle.js:2:13853 at t.LegacyFunctionLoader. (C:\Program Files (x86)\SiteExtensions\Functions\4.14.0\workers\node\dist\src\worker-bundle.js:2:14092) at Generator.next () at o (C:\Program Files (x86)\SiteExtensions\Functions\4.14.0\workers\node\dist\src\worker-bundle.js:2:12538) at processTicksAndRejections (node:internal/process/task_queues:96:5)
Thanks in advance
Todd
While trying to get all the blobs using getBlobToStream() following error is displayed.How can I handle it?
I also came across "ExponentialRetryPolicyFilter" but not sure how to use it.
So far did not find any code related to it.
blobService.listBlobsSegmentedWithPrefix(containerName, path, null, (err, data) => {
data.entries.forEach(entry => {
var options = {
rangeStart: 0,
rangeEnd: entry.contentLength
};
if (fs.existsSync(fileUploadPath)) {
var sourceFilePath = fileUploadPath + '/' + project.id + '/' + entry.name;
if (!fs.existsSync(sourceFilePath)) {
fs.mkdir(require('path').dirname(sourceFilePath), { recursive: true }, (err) => {
if (err) {
console.log("Failed to mkdir:" + err);
}
blobService.getBlobToStream(containerName, entry.name, fs.createWriteStream(sourceFilePath, { flags: 'a' }), options, (error, data) => {
if (error) {
console.log('getblobtostream error', error)
}
});
});
}
Error:
getblobtostream error Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
getblobtostream error Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (D:\tiger3\Nexus-services\node_modules\request\request.js:816:19)
{
code: 'ESOCKETTIMEDOUT',
connect: false
}
ESOCKETTIMEDOUT is basically network error and it can happen due to poor or unstable network or due to continuous heavy usage. Try to add retry filter on client library side.
You can try use it before getBlobToStream to create blobservice object .
var azure = require('azure-storage');
var retryOperations = new azure.ExponentialRetryPolicyFilter();
var blobService = azure.createBlobService().withFilter(retryOperations)
See azure storage-nodejs ,use-blob-storage. GitHub
References:
ESOCKETTIMEDOUT error · Issue #604 · Azure/azure-storage-node ·
GitHub
Using BlobService.getBlobToStream from javascript client SDK · Issue
· GitHub
I have written code to establish a SFTP connection and transfer files to the SFTP server using Node.js sftp.put command. I'm getting the following error while transferring the file. I can establish the connection successfully. But I cannot read/write files to the server. I have attached the code below
Code
let sftp = new client();
let filename = "sound.mp3";
const filePath = path.join(__dirname, '../audio', filename)
const putConfig = {
flags: 'w', // w - write and a - append
encoding: null, // use null for binary files
mode: 0o666, // mode to use for created file (rwx)
autoClose: true // automatically close the write stream when finished
};
sftp.connect({
host: 'host',
port: '22',
username: 'xxxx',
password: 'xxx'
}).then(() => {
return sftp.put(filePath, '/', putConfig)
}).then(data => {
console.log(data, 'the data info');
}).catch(err => {
console.log(err, 'catch error');
});
Error
Error: put->put: Failure /data
at fmtError (D:\project\node_modules\ssh2-sftp-client\src\utils.js:53:18)
at SftpClient.put (D:\project\node_modules\ssh2-sftp-client\src\index.js:684:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 4,
custom: true
}
D:\project\node_modules\ssh2\lib\protocol\crypto\poly1305.js:20
function J(a){if(b.onAbort)b.onAbort(a);L(a);O=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnY
RuntimeError: abort(Error: put->put: Failure /data). Build with -s ASSERTIONS=1 for more info.
at process.J (D:\project\node_modules\ssh2\lib\protocol\crypto\poly1305.js:20:53)
at process.emit (events.js:210:5)
at process.EventEmitter.emit (domain.js:475:20)
at processPromiseRejections (internal/process/promises.js:201:33)
at processTicksAndRejections (internal/process/task_queues.js:94:32)
The second argument of SftpClient.put is a path to the target remote file, not only path to the target remote folder.
So it should be like:
return sftp.put(filePath, '/' + filename, putConfig)
Error code looks like:
{ Error: ENOENT: no such file or directory, open 'sad' errno: -2, code: 'ENOENT', syscall: 'open', path: 'sad' }
where 'sad' is the name of file I would like to write to and it doesn't exist.
Code looks like this:
fs.writeFile(filename, JSON_string, { flag: 'w' }, function(err){
if(err){
return console.error(err);
}
return JSON_string;
});
There are other similar questions, but they are all wrong in their path, starting or not starting with /, I just want to write a file on root from where I run this node.js application (it is also initialized with npm in this directory..).
Running with
sudo node server4.js
Doesnt work either.
Changing flags to w+ or wx or whatever, doesn't help.
Code works if file exists.
Node v9+.
I need to use writeFile() function.
This is working for me, please check if this works in your system:
var fs = require('fs')
fs.writeFile('./myfile.txt', 'Content to write', { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('./myfile.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
console.log(data);
});
});
(besides writing it also reads to confirm)
I am downloading a file from Google Drive using nodejs module googleapis 7.1.0. When I do authentication or retrieve metadata, everything goes fine.
When the download is finished and the application is supposed to end, I get two different outcomes, both seem to be wrong.
In Windows, the program just hangs indefinitely and produces no output, no exception. I just hangs.
On FreeBSD, I get the following stack trace:
buffer.js:377
throw new Error('toString failed');
^
Error: toString failed
at Buffer.toString (buffer.js:377:11)
at BufferList.toString (/usr/home/jvavruska/gdrive/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/node_modules/bl/bl.js:166:33)
at Request.<anonymous> (/usr/home/jvavruska/gdrive/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/request.js:1035:36)
at emitOne (events.js:82:20)
at Request.emit (events.js:169:7)
at IncomingMessage.<anonymous> (/usr/home/jvavruska/gdrive/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/request.js:1003:12)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:913:12)
at nextTickCallbackWith2Args (node.js:442:9)
I use node 4.4.5 on both machines (Windows 10 and FreeBSD 10) and the same version of googleapis (7.1.0).
The final function that does the download is here. name is read from file metadat using get API, auth is the auth object created from google.auth.OAuth2, googleDrive is proxy of google.drive('v3') and google is from google = require('googleapis') :
function googleDownload ( name, fileId, auth, downloadDirectory ) {
downloadDirectory = downloadDirectory || 'c:\\playground' ;
var targetFileName = path.join( downloadDirectory, name );
var dest = fs.createWriteStream(targetFileName);
console.log(`Starting download of ${fileId} as ${name}`);
googleDrive.files.get({
fileId: fileId,
auth: auth,
alt: 'media'
},
(err, response) => {
if(err) { console.log("Download error: ", err);}
else { console.log("Download completed."); }
})
.on('end', () => { console.log('All data received.'); })
.on('finish', () => { console.log('All data written.'); })
.on('close', () => { console.log('Connectin closed.'); })
.on('error', (err) => { console.log('Error during download: ', err); })
.pipe(dest);
}
By looking into the code I was not able to find a direct link between the place where the error is thrown and what was actually supposed to happen. I just noticed that the googleapis bundle seems to duplicate a number of methods or functions available in NodeJS API but cannot say what is the impact on the error.