aadsm / jsmediatags

Media Tags Reader (ID3, MP4, FLAC)
Other
745 stars 128 forks source link

Included the audio file's path with returned tags #110

Closed Zero-1729 closed 5 years ago

Zero-1729 commented 5 years ago

We might want our (onSuccess) callback function to also return the path of the audio file it read along with its tags. So that we can properly construct the following track object for example;

conts jsm = require('jsmediatags')

new jsm.Reader('/path/to/file').setTagsToRead(['
    title', 'artist', 'album', 'genre', 'picture', 'year'
]).read({
    onSuccess: (tag, path) => {
        var raw_title = path.slice(path.lastIndexOf('/')+1, path.length)
        raw_title = raw_title.split('.')[0]

        console.log({
            title: !tag.tags.title ? raw_title : tag.tags.title,
            artist: !tag.tags.artist ? 'Unknown' : tag.tags.artist,
            // ... 
        })
    },
    onError: (error) => {
        console.debug(error)   
    }
})
Zero-1729 commented 5 years ago

It seems there is a way to achieve the aforementioned goal without modifying the code base. I am therefore going to close this PR.

The method employs the use of Javascript Promises.

I have outlined the approach in the following JS code snippet below for the sake of providing anyone in the future with a method to still keep track of the audio file's path when handling the resolved tags;

conts jsm = require('jsmediatags')

var filepath = '/path/to/audio.mp3'

new Promise((resolve, reject) => {
    new jsm.Reader(filepath).setTagsToRead([
        'title', 'artist', 'album', 'genre', 'picture', 'year'
    ]).read({
        onSuccess: (tag) => {
            resolve({
                tags: tag.tags,
                track_path: filepath
            })
        },
        onError: (err) => {
            reject({ 
                error: err, 
                track_path: filepath 
            })
        }
    })
}).then(resolved_obj => {
    // Here we simply obtain the JS Object containing the scanned tags and filepath
}).catch(error_obj => {
    // And we handle error reporting using the JS Object
    // ... containing the details of the scan error
    // ... aswell as the audio's filepath
})

Any additional questions or requests for clarifications are welcome.