'fs.createWriteStream, no such file or directory, open Nodejs

I want to save files that I am getting from another server on my server but the problem is when I am calling createWriteStream it giving me the error :

no such file or directory, open E:\pathtoproject\myproject\public\profile_14454.jpg

Here is my code which is in E:\pathtoproject\myproject\modules\dowload.js :

request.head(infos.profile_pic, function(err, res, body) {
  const completeFileName = '../public/profile_14454.' + res.headers['content-type'].split('/')[1];
  var imageStream = fs.createWriteStream(completeFileName);
  imageStream.on('open', function(fd) {
    console.log("File open");
    request(infos.profile_pic).pipe(imageStream).on('close', function(body) {
      consoleLog('Profile pic saved');
      console.log('This is the content of body');
      console.log(body);
      connection.query('UPDATE user set photo=? where id=?', [completeFileName, lastID], function(err, result, fields) {
        if (err) {
          consoleLog('Error while update the profile pic');
        }
      });
    })
  });
});

When I removed the directory ../public/ and leave only the name of the file profile_14454.' + res.headers['content-type'].split('/')[1] , it worked but the file was saved in the root directory of the project (E:\pathtoproject\myproject\).

What's wrong in what I am doing? How can I have the file saved under public directory?

I am using nodeJS 8.9.4



Solution 1:[1]

I tried with my small code .

var fs = require("fs");
var data = 'Simply Easy Learning';

// Create a writable stream
var writerStream = fs.createWriteStream('./airo/output.txt');

// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();

// Handle stream events --> finish, and error
writerStream.on('finish', function() {
    console.log("Write completed.");
});

writerStream.on('error', function(err){
   console.log(err.stack);
});

console.log("Program Ended");

My code is in this path E:\syed ayesha\nodejs\nodejs now I want to store my file in airo folder which is in this path. So I used one dot for storing. Hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Syed Ayesha Bebe