Retrieving files from Directory Node Js

前端 未结 2 610
刺人心
刺人心 2021-02-06 21:08

I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.

var fs = require(\'fs\');
var files = fs.readdirSync(\'./ap         


        
相关标签:
2条回答
  • 2021-02-06 21:11

    If you are using relative path when calling readdirSync, make sure it is relative to process.cwd(). However, "require" should be relative to the current script.

    For example, given the following structure

    server.js (node process)
    /lib/importer.js (the current script)
    /lib/application/models/
    

    you may need to write importer.js as:

    var fs = require('fs');
    var files = fs.readdirSync('./lib/application/models/');
    for (var i in files) {
      var definition = require('./application/models/' + files[i]).Model;
      console.log('Model Loaded: ' + files[i]);
    }
    
    0 讨论(0)
  • 2021-02-06 21:32

    Have you tried the following?

    var files = fs.readdirSync(__dirname+'/application/models/');
    
    0 讨论(0)
提交回复
热议问题