5561

Set Path for Mounted Network Drive in Node

Question:

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?

<blockquote>

(node:4796) UnhandledPromiseRejectionWarning:<br /> 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)<br /> at callback (C:\app\location\node_modules\child-process-promise\lib\index.js:33:27)<br /> at ChildProcess.exithandler (child_process.js:279:5)<br /> at ChildProcess.emit (events.js:159:13)<br /> at maybeClose (internal/child_process.js:943:16)<br /> at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)<br /> name: 'ChildProcessError',<br /> code: 2,<br /> childProcess:

{ ChildProcess: { [Function: ChildProcess] super_: [Function] },<br /> fork: [Function],<br /> _forkChild: [Function],<br /> exec: [Function],<br /> execFile: [Function],<br /> spawn: [Function],<br /> spawnSync: [Function: spawnSync],<br /> execFileSync: [Function: execFileSync],<br /> execSync: [Function: execSync] },<br /> stdout: '',<br /> stderr: 'System error 67 has occurred.\r\n\r\nThe network name cannot be found.\r\n\r\n' }

</blockquote>

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 }) });

Answer1:

To write from a REST Service hosted in IIS, you will need to properly set the permissions on the server.

<blockquote> <ol><li>You will need to set the identity of the Application Pool of your site.</li> </ol></blockquote>

<a href="https://i.stack.imgur.com/o0Ymj.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/o0Ymj.png" data-original="https://i.stack.imgur.com/o0Ymj.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

<blockquote> <ol start="2"><li>You will need to grant write permissions to match that account or account group to the folder that you are trying to write to.</li> </ol></blockquote>

Note: If you map a folder to a network drive letter through the OS, it is only defined at the user account level.

<a href="https://i.stack.imgur.com/reFnZ.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/reFnZ.png" data-original="https://i.stack.imgur.com/reFnZ.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

<blockquote> <ol start="3"><li>So, if you have mapped the folder location to a drive letter (in this case 'X:'), instead of writing to </li> </ol></blockquote> 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.

Answer2:

I am not sure what error you got, so here are a couple tips for when you are using <a href="https://www.npmjs.com/package/windows-network-drive" rel="nofollow">windows-network-drive. </a>

<strong>Escape Special Characters</strong>

Windows uses \ to separate directories. <a href="https://www.w3schools.com/js/js_strings.asp" rel="nofollow">\ is a special character</a> in a JavaScript string and must be escaped like this \\. e.g. C:\file.txt would be C:\\file.txt in a string.

<strong>Use POSIX Separation Character When You Can</strong>

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.

<strong>Example</strong>

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!'); }); });

Recommend

  • gulp Cannot find module 'readable-stream/transform'
  • Error while adding android platform for cordova
  • Error while running execFileSync in packaged Electron app
  • Convert PDF to PNG Node.JS
  • Web Action returns HTTP 200 response with empty body
  • Error building libxmljs for node.js
  • NodeJs/Formidable, Uploading Images error
  • Overriding implicit styles in nested controls
  • How to select the optimal key in map reduce?
  • Pdflatex run crashes when executed from Java (on Windows)
  • Error: Please install Android target: “android-22” when SDK manager shows it is installed
  • Property 'catch' does not exist on type 'PromiseLike
  • How to send None with Signals across threads?
  • I have a modal that opens a second modal and cannot close the first modal if open then close the sec
  • Socket io in node app on google app engine
  • Why is my req.body always empty on POST?
  • Copying rows in a database when rows have children
  • Passing information to server-side function in a Google Docs Add On
  • How to Add Polymorphic Comments to Feed?
  • Why doesnt this Java loop in a thread work?
  • select function not working in 3.5.4 version of d3.js
  • How to use jQuery's $.post() method with async/await and typescript
  • How to get latest version of a artifact on Bintray using JSONP
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • error importing numpy
  • How can I sort a a table with VBA with given text condition?
  • Very simple C++ DLL that can be called from .net
  • Xamarin Forms - UWP Fonts
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • req.body is undefined - nodejs
  • Updating server-side rendering client-side
  • Modifying destination and filename of gulp-svg-sprite
  • Importing jscolor library in angular 2
  • Rearranging Cells in UITableView Bug & Saving Changes
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Proper way to use connect-multiparty with express.js?
  • Understanding cpu registers
  • How do I configure my settings file to work with unit tests?
  • Conditional In-Line CSS for IE and Others?
  • How do I use LINQ to get all the Items that have a particular SubItem?