1

I try to read all file names in my image folder avatar but getting the error.

Cannot find name 'require'.

I have a lot of files in avatar and want list them as <images>elements. Thats why I tried to get the file-names in the folder .

I'm using Angular 4.2.5 and Webpack

import { Component, Input } from '@angular/core';


var filesystem = require('fs')

const AVATAR_PATH = '../assets/img/avatar'

@Component({
    selector: 'profile',
    templateUrl: 'profile.component.html',
    styleUrls: ['profile.component.scss']
})
export class ProfileComponent {

    path = AVATAR_PATH;


  constructor() {
    console.log(this.getFileNames(AVATAR_PATH));
  }


  getFileNames(dir)
  {
    let results =[];
    filesystem.readdir(dir).forEach(function(file) {

      file = dir+'/'+file;
      results.push(file);
    });

    return results;
  }
}

My folder structure is:

-app
---|room
------|profile
---|assets
------|image
----------|avatar
Samy
  • 1,013
  • 3
  • 15
  • 25
  • fs is a node built-in library; why are you trying to run angular on nodejs? – nadavvadan Jul 02 '17 at 13:24
  • then, how can I read local files in anguar without fs ? – Samy Jul 02 '17 at 13:27
  • your folder structure – Aravind Jul 02 '17 at 13:28
  • 2
    You can't. angular executes **in the browser**. JavaScript executing in the browser is not allowed to access local files. And the files, anyway, are on your server, not on the browser machine. – JB Nizet Jul 02 '17 at 13:29
  • Angular does not have access to the file system, since it runs in a browser, which is a sandboxed environment. What are you trying to achieve or create? – nadavvadan Jul 02 '17 at 13:29
  • since I can't access to the file system, how can I then just get the filenames, need i type everything in an array as string ? – Samy Jul 02 '17 at 13:37
  • If you want to do it dynamically, you'd need a web server to send you the data from the machine; again, what are you trying to achieve? – nadavvadan Jul 02 '17 at 13:38
  • frontend JS applications communicate with their backend using HTTP. Your backend REST server is free to read anything it wants from its file system, and to respond to HTTP requests from your angular application asking for file names. – JB Nizet Jul 02 '17 at 13:38
  • I just wanted get dynamically the file-names to list them as elements and set the src with the file-names – Samy Jul 02 '17 at 13:39
  • So, expose the list of file names from a REST resource in your backend. – JB Nizet Jul 02 '17 at 13:40

0 Answers0