简体   繁体   中英

How to write a file to a remote server url on node js using fs?

I need to write a file on a remote server folder, i'm using fs on nodejs. This is my code, the function return with no errors but it doesn´t write the file on the folder.

fs.writeFile('https:/someurl.com/Content/myfiles/message.txt', 'Hello Node.js', 'utf8', (err) => {
      console.log(err)
    })

You can't do it. fs is only for the filesystem where the code is being executed.

The only way is that the server you are pointing to should have an API at which, by passing certain parameters, write the file in that path.

You cannot use fs to access remote file systems, you have to relay on third party libraries.

Upload:

You can use a third party library like ftp to upload to a public ftp:

var Client = require('ftp');
  var fs = require('fs');

  var c = new Client({ host: 'someurl.com', port: 21});
  c.on('ready', function() {
    c.cwd('/Content/myfiles', function(err) {
      if(!err) {
        c.put('/local/path/message.txt', 'message.txt', function(err) {
          if (err) throw err;
          c.end();
        });
      }
    });
  });
  c.connect();

Assuming you have access to that server, ftp also provides support for servers that require simple authentication.

Download:

You can use request library to fetch the file, then use fs to write it to your file system:

var request = require('request');
request.get('https:/someurl.com/Content/myfiles/message.txt', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        fs.writeFile('message.txt', body, 'utf8', (err) => {
            console.log(err)
        })
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM